diff --git a/server/node_modules/express/History.md b/server/node_modules/express/History.md old mode 100755 new mode 100644 index 6c232529..3ce212fa --- a/server/node_modules/express/History.md +++ b/server/node_modules/express/History.md @@ -1,3 +1,190 @@ +4.12.4 / 2015-05-17 +=================== + + * deps: accepts@~1.2.7 + - deps: mime-types@~2.0.11 + - deps: negotiator@0.5.3 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: finalhandler@0.3.6 + - deps: debug@~2.2.0 + - deps: on-finished@~2.2.1 + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + * deps: serve-static@~1.9.3 + - deps: send@0.12.3 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +4.12.3 / 2015-03-17 +=================== + + * deps: accepts@~1.2.5 + - deps: mime-types@~2.0.10 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: finalhandler@0.3.4 + - deps: debug@~2.1.3 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + * deps: serve-static@~1.9.2 + - deps: send@0.12.2 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +4.12.2 / 2015-03-02 +=================== + + * Fix regression where `"Request aborted"` is logged using `res.sendFile` + +4.12.1 / 2015-03-01 +=================== + + * Fix constructing application with non-configurable prototype properties + * Fix `ECONNRESET` errors from `res.sendFile` usage + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + * Fix wrong `code` on aborted connections from `res.sendFile` + * deps: merge-descriptors@1.0.0 + +4.12.0 / 2015-02-23 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: accepts@~1.2.4 + - Fix preference sorting to be stable for long acceptable lists + - deps: mime-types@~2.0.9 + - deps: negotiator@0.5.1 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + * deps: serve-static@~1.9.1 + - deps: send@0.12.1 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +4.11.2 / 2015-02-01 +=================== + + * Fix `res.redirect` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.2.3 + - deps: mime-types@~2.0.8 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +4.11.1 / 2015-01-20 +=================== + + * deps: send@0.11.1 + - Fix root path disclosure + * deps: serve-static@~1.8.1 + - Fix redirect loop in Node.js 0.11.14 + - Fix root path disclosure + - deps: send@0.11.1 + +4.11.0 / 2015-01-13 +=================== + + * Add `res.append(field, val)` to append headers + * Deprecate leading `:` in `name` for `app.param(name, fn)` + * Deprecate `req.param()` -- use `req.params`, `req.body`, or `req.query` instead + * Deprecate `app.param(fn)` + * Fix `OPTIONS` responses to include the `HEAD` method properly + * Fix `res.sendFile` not always detecting aborted connection + * Match routes iteratively to prevent stack overflows + * deps: accepts@~1.2.2 + - deps: mime-types@~2.0.7 + - deps: negotiator@0.5.0 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + * deps: serve-static@~1.8.0 + - deps: send@0.11.0 + +4.10.8 / 2015-01-13 +=================== + + * Fix crash from error within `OPTIONS` response handler + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + +4.10.7 / 2015-01-04 +=================== + + * Fix `Allow` header for `OPTIONS` to not contain duplicate methods + * Fix incorrect "Request aborted" for `res.sendFile` when `HEAD` or 304 + * deps: debug@~2.1.1 + * deps: finalhandler@0.3.3 + - deps: debug@~2.1.1 + - deps: on-finished@~2.2.0 + * deps: methods@~1.1.1 + * deps: on-finished@~2.2.0 + * deps: serve-static@~1.7.2 + - Fix potential open redirect when mounted at root + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +4.10.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +4.10.5 / 2014-12-10 +=================== + + * Fix `res.send` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.1.4 + - deps: mime-types@~2.0.4 + * deps: type-is@~1.5.4 + - deps: mime-types@~2.0.4 + +4.10.4 / 2014-11-24 +=================== + + * Fix `res.sendfile` logging standard write errors + +4.10.3 / 2014-11-23 +=================== + + * Fix `res.sendFile` logging standard write errors + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + 4.10.2 / 2014-11-09 =================== @@ -584,6 +771,182 @@ - `app.route()` - Proxy to the app's `Router#route()` method to create a new route - Router & Route - public API +3.20.3 / 2015-05-17 +=================== + + * deps: connect@2.29.2 + - deps: body-parser@~1.12.4 + - deps: compression@~1.4.4 + - deps: connect-timeout@~1.6.2 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: errorhandler@~1.3.6 + - deps: finalhandler@0.3.6 + - deps: method-override@~2.3.3 + - deps: morgan@~1.5.3 + - deps: qs@2.4.2 + - deps: response-time@~2.3.1 + - deps: serve-favicon@~2.2.1 + - deps: serve-index@~1.6.4 + - deps: serve-static@~1.9.3 + - deps: type-is@~1.6.2 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +3.20.2 / 2015-03-16 +=================== + + * deps: connect@2.29.1 + - deps: body-parser@~1.12.2 + - deps: compression@~1.4.3 + - deps: connect-timeout@~1.6.1 + - deps: debug@~2.1.3 + - deps: errorhandler@~1.3.5 + - deps: express-session@~1.10.4 + - deps: finalhandler@0.3.4 + - deps: method-override@~2.3.2 + - deps: morgan@~1.5.2 + - deps: qs@2.4.1 + - deps: serve-index@~1.6.3 + - deps: serve-static@~1.9.2 + - deps: type-is@~1.6.1 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: merge-descriptors@1.0.0 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +3.20.1 / 2015-02-28 +=================== + + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + +3.20.0 / 2015-02-18 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: connect@2.29.0 + - Use `content-type` to parse `Content-Type` headers + - deps: body-parser@~1.12.0 + - deps: compression@~1.4.1 + - deps: connect-timeout@~1.6.0 + - deps: cookie-parser@~1.3.4 + - deps: cookie-signature@1.0.6 + - deps: csurf@~1.7.0 + - deps: errorhandler@~1.3.4 + - deps: express-session@~1.10.3 + - deps: http-errors@~1.3.1 + - deps: response-time@~2.3.0 + - deps: serve-index@~1.6.2 + - deps: serve-static@~1.9.1 + - deps: type-is@~1.6.0 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +3.19.2 / 2015-02-01 +=================== + + * deps: connect@2.28.3 + - deps: compression@~1.3.1 + - deps: csurf@~1.6.6 + - deps: errorhandler@~1.3.3 + - deps: express-session@~1.10.2 + - deps: serve-index@~1.6.1 + - deps: type-is@~1.5.6 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + +3.19.1 / 2015-01-20 +=================== + + * deps: connect@2.28.2 + - deps: body-parser@~1.10.2 + - deps: serve-static@~1.8.1 + * deps: send@0.11.1 + - Fix root path disclosure + +3.19.0 / 2015-01-09 +=================== + + * Fix `OPTIONS` responses to include the `HEAD` method property + * Use `readline` for prompt in `express(1)` + * deps: commander@2.6.0 + * deps: connect@2.28.1 + - deps: body-parser@~1.10.1 + - deps: compression@~1.3.0 + - deps: connect-timeout@~1.5.0 + - deps: csurf@~1.6.4 + - deps: debug@~2.1.1 + - deps: errorhandler@~1.3.2 + - deps: express-session@~1.10.1 + - deps: finalhandler@0.3.3 + - deps: method-override@~2.3.1 + - deps: morgan@~1.5.1 + - deps: serve-favicon@~2.2.0 + - deps: serve-index@~1.6.0 + - deps: serve-static@~1.8.0 + - deps: type-is@~1.5.5 + * deps: debug@~2.1.1 + * deps: methods@~1.1.1 + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +3.18.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +3.18.5 / 2014-12-11 +=================== + + * deps: connect@2.27.6 + - deps: compression@~1.2.2 + - deps: express-session@~1.9.3 + - deps: http-errors@~1.2.8 + - deps: serve-index@~1.5.3 + - deps: type-is@~1.5.4 + +3.18.4 / 2014-11-23 +=================== + + * deps: connect@2.27.4 + - deps: body-parser@~1.9.3 + - deps: compression@~1.2.1 + - deps: errorhandler@~1.2.3 + - deps: express-session@~1.9.2 + - deps: qs@2.3.3 + - deps: serve-favicon@~2.1.7 + - deps: serve-static@~1.5.1 + - deps: type-is@~1.5.3 + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + 3.18.3 / 2014-11-09 =================== diff --git a/server/node_modules/express/LICENSE b/server/node_modules/express/LICENSE old mode 100755 new mode 100644 index 0f3c7678..aa927e44 --- a/server/node_modules/express/LICENSE +++ b/server/node_modules/express/LICENSE @@ -1,6 +1,8 @@ (The MIT License) Copyright (c) 2009-2014 TJ Holowaychuk +Copyright (c) 2013-2014 Roman Shtylman +Copyright (c) 2014-2015 Douglas Christopher Wilson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/server/node_modules/express/Readme.md b/server/node_modules/express/Readme.md old mode 100755 new mode 100644 index 24bc5822..8da83a51 --- a/server/node_modules/express/Readme.md +++ b/server/node_modules/express/Readme.md @@ -4,7 +4,8 @@ [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] - [![Build Status][travis-image]][travis-url] + [![Linux Build][travis-image]][travis-url] + [![Windows Build][appveyor-image]][appveyor-url] [![Test Coverage][coveralls-image]][coveralls-url] ```js @@ -18,7 +19,7 @@ app.get('/', function (req, res) { app.listen(3000) ``` -### Installation +## Installation ```bash $ npm install express @@ -86,7 +87,7 @@ $ npm start ## Examples - To view the examples, clone the Express repo & install the dependancies: + To view the examples, clone the Express repo and install the dependencies: ```bash $ git clone git://github.com/strongloop/express.git --depth 1 @@ -102,14 +103,14 @@ $ node examples/content-negotiation ## Tests - To run the test suite, first install the dependancies, then run `npm test`: + To run the test suite, first install the dependencies, then run `npm test`: ```bash $ npm install $ npm test ``` -### People +## People The original author of Express is [TJ Holowaychuk](https://github.com/tj) [![TJ's Gratipay][gratipay-image-visionmedia]][gratipay-url-visionmedia] @@ -117,19 +118,21 @@ The current lead maintainer is [Douglas Christopher Wilson](https://github.com/d [List of all contributors](https://github.com/strongloop/express/graphs/contributors) -### License +## License [MIT](LICENSE) -[npm-image]: https://img.shields.io/npm/v/express.svg?style=flat +[npm-image]: https://img.shields.io/npm/v/express.svg [npm-url]: https://npmjs.org/package/express -[downloads-image]: https://img.shields.io/npm/dm/express.svg?style=flat +[downloads-image]: https://img.shields.io/npm/dm/express.svg [downloads-url]: https://npmjs.org/package/express -[travis-image]: https://img.shields.io/travis/strongloop/express.svg?style=flat +[travis-image]: https://img.shields.io/travis/strongloop/express/master.svg?label=linux [travis-url]: https://travis-ci.org/strongloop/express -[coveralls-image]: https://img.shields.io/coveralls/strongloop/express.svg?style=flat +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/express/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/express +[coveralls-image]: https://img.shields.io/coveralls/strongloop/express/master.svg [coveralls-url]: https://coveralls.io/r/strongloop/express?branch=master -[gratipay-image-visionmedia]: https://img.shields.io/gratipay/visionmedia.svg?style=flat +[gratipay-image-visionmedia]: https://img.shields.io/gratipay/visionmedia.svg [gratipay-url-visionmedia]: https://gratipay.com/visionmedia/ -[gratipay-image-dougwilson]: https://img.shields.io/gratipay/dougwilson.svg?style=flat +[gratipay-image-dougwilson]: https://img.shields.io/gratipay/dougwilson.svg [gratipay-url-dougwilson]: https://gratipay.com/dougwilson/ diff --git a/server/node_modules/express/index.js b/server/node_modules/express/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/lib/application.js b/server/node_modules/express/lib/application.js old mode 100755 new mode 100644 index 2fbb5503..5ec44248 --- a/server/node_modules/express/lib/application.js +++ b/server/node_modules/express/lib/application.js @@ -1,5 +1,14 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + /** * Module dependencies. + * @api private */ var finalhandler = require('finalhandler'); @@ -25,6 +34,13 @@ var slice = Array.prototype.slice; var app = exports = module.exports = {}; +/** + * Variable for trust proxy inheritance back-compat + * @api private + */ + +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + /** * Initialize the server. * @@ -58,10 +74,23 @@ app.defaultConfiguration = function(){ this.set('subdomain offset', 2); this.set('trust proxy', false); + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); + debug('booting in %s mode', env); - // inherit protos - this.on('mount', function(parent){ + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; + } + + // inherit protos this.request.__proto__ = parent.request; this.response.__proto__ = parent.response; this.engines.__proto__ = parent.engines; @@ -327,6 +356,13 @@ app.set = function(setting, val){ case 'trust proxy': debug('compile trust proxy %s', val); this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + break; } @@ -563,7 +599,7 @@ app.listen = function(){ * Log error using console.error. * * @param {Error} err -* @api public +* @api private */ function logerror(err){ diff --git a/server/node_modules/express/lib/express.js b/server/node_modules/express/lib/express.js old mode 100755 new mode 100644 index 8a6c2846..bb8d8082 --- a/server/node_modules/express/lib/express.js +++ b/server/node_modules/express/lib/express.js @@ -28,8 +28,8 @@ function createApplication() { app.handle(req, res, next); }; - mixin(app, proto); - mixin(app, EventEmitter.prototype); + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); app.request = { __proto__: req, app: app }; app.response = { __proto__: res, app: app }; diff --git a/server/node_modules/express/lib/middleware/init.js b/server/node_modules/express/lib/middleware/init.js old mode 100755 new mode 100644 index c09cf0c6..1e3e903f --- a/server/node_modules/express/lib/middleware/init.js +++ b/server/node_modules/express/lib/middleware/init.js @@ -1,6 +1,6 @@ /** * Initialization middleware, exposing the - * request and response to eachother, as well + * request and response to each other, as well * as defaulting the X-Powered-By header field. * * @param {Function} app diff --git a/server/node_modules/express/lib/middleware/query.js b/server/node_modules/express/lib/middleware/query.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/lib/request.js b/server/node_modules/express/lib/request.js old mode 100755 new mode 100644 index 483ee1c1..e52dfe55 --- a/server/node_modules/express/lib/request.js +++ b/server/node_modules/express/lib/request.js @@ -63,12 +63,12 @@ req.header = function(name){ * the best match when true, otherwise `undefined`, in which * case you should respond with 406 "Not Acceptable". * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json", a comma-delimted list such as "json, html, text/plain", + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", * an argument list such as `"json", "html", "text/plain"`, * or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. + * or array is given, the _best_ match, if any is returned. * * Examples: * @@ -200,13 +200,20 @@ req.range = function(size){ * @api public */ -req.param = function(name, defaultValue){ +req.param = function param(name, defaultValue) { var params = this.params || {}; var body = this.body || {}; var query = this.query || {}; + + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; if (null != body[name]) return body[name]; if (null != query[name]) return query[name]; + return defaultValue; }; @@ -261,7 +268,7 @@ defineGetter(req, 'protocol', function protocol(){ : 'http'; var trust = this.app.get('trust proxy fn'); - if (!trust(this.connection.remoteAddress)) { + if (!trust(this.connection.remoteAddress, 0)) { return proto; } @@ -371,7 +378,7 @@ defineGetter(req, 'hostname', function hostname(){ var trust = this.app.get('trust proxy fn'); var host = this.get('X-Forwarded-Host'); - if (!host || !trust(this.connection.remoteAddress)) { + if (!host || !trust(this.connection.remoteAddress, 0)) { host = this.get('Host'); } @@ -412,7 +419,7 @@ defineGetter(req, 'fresh', function(){ // 2xx or 304 as per rfc2616 14.26 if ((s >= 200 && s < 300) || 304 == s) { - return fresh(this.headers, this.res._headers); + return fresh(this.headers, (this.res._headers || {})); } return false; diff --git a/server/node_modules/express/lib/response.js b/server/node_modules/express/lib/response.js old mode 100755 new mode 100644 index 34e46ad7..b759eb95 --- a/server/node_modules/express/lib/response.js +++ b/server/node_modules/express/lib/response.js @@ -1,5 +1,13 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + /** * Module dependencies. + * @api private */ var contentDisposition = require('content-disposition'); @@ -159,15 +167,12 @@ res.send = function send(body) { this.set('Content-Length', len); } - // method check - var isHead = req.method === 'HEAD'; - - // ETag support - if (len !== undefined && (isHead || req.method === 'GET')) { - var etag = app.get('etag fn'); - if (etag && !this.get('ETag')) { - etag = etag(chunk, encoding); - etag && this.set('ETag', etag); + // populate ETag + var etag; + var generateETag = len !== undefined && app.get('etag fn'); + if (typeof generateETag === 'function' && !this.get('ETag')) { + if ((etag = generateETag(chunk, encoding))) { + this.set('ETag', etag); } } @@ -182,14 +187,14 @@ res.send = function send(body) { chunk = ''; } - // skip body for HEAD - if (isHead) { + if (req.method === 'HEAD') { + // skip body for HEAD this.end(); + } else { + // respond + this.end(chunk, encoding); } - // respond - this.end(chunk, encoding); - return this; }; @@ -398,8 +403,8 @@ res.sendFile = function sendFile(path, options, fn) { if (fn) return fn(err); if (err && err.code === 'EISDIR') return next(); - // next() all but aborted errors - if (err && err.code !== 'ECONNABORT') { + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { next(err); } }); @@ -467,8 +472,8 @@ res.sendfile = function(path, options, fn){ if (fn) return fn(err); if (err && err.code === 'EISDIR') return next(); - // next() all but aborted errors - if (err && err.code !== 'ECONNABORT') { + // next() all but write errors + if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') { next(err); } }); @@ -636,6 +641,35 @@ res.attachment = function attachment(filename) { return this; }; +/** + * Append additional header `field` with value `val`. + * + * Example: + * + * res.append('Link', ['', '']); + * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * res.append('Warning', '199 Miscellaneous warning'); + * + * @param {String} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @api public + */ + +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; + + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val]; + } + + return this.set(field, value); +}; + /** * Set header `field` to `val`, or pass * an object of header fields. @@ -841,9 +875,9 @@ res.redirect = function redirect(url) { if (this.req.method === 'HEAD') { this.end(); + } else { + this.end(body); } - - this.end(body); }; /** @@ -907,6 +941,17 @@ res.render = function(view, options, fn){ // pipe the send file stream function sendfile(res, file, options, callback) { var done = false; + var streaming; + + // request aborted + function onaborted() { + if (done) return; + done = true; + + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); + } // directory function ondirectory() { @@ -932,25 +977,39 @@ function sendfile(res, file, options, callback) { callback(); } + // file + function onfile() { + streaming = false; + } + // finished function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); if (err) return onerror(err); if (done) return; setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } + if (done) return; done = true; - - // response finished before end of file - var err = new Error('Request aborted'); - err.code = 'ECONNABORT'; - callback(err); + callback(); }); } + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); file.on('end', onend); file.on('error', onerror); - file.on('directory', ondirectory); + file.on('file', onfile); + file.on('stream', onstream); onFinished(res, onfinish); if (options.headers) { diff --git a/server/node_modules/express/lib/router/index.js b/server/node_modules/express/lib/router/index.js old mode 100755 new mode 100644 index b3a42e29..209f881b --- a/server/node_modules/express/lib/router/index.js +++ b/server/node_modules/express/lib/router/index.js @@ -8,6 +8,7 @@ var Layer = require('./layer'); var methods = require('methods'); var mixin = require('utils-merge'); var debug = require('debug')('express:router'); +var deprecate = require('depd')('express'); var parseUrl = require('parseurl'); var utils = require('../utils'); @@ -81,9 +82,10 @@ var proto = module.exports = function(options) { * @api public */ -proto.param = function(name, fn){ +proto.param = function param(name, fn) { // param logic - if ('function' == typeof name) { + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); this._params.push(name); return; } @@ -94,6 +96,7 @@ proto.param = function(name, fn){ var ret; if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); name = name.substr(1); } @@ -152,9 +155,7 @@ proto.handle = function(req, res, done) { if (req.method === 'OPTIONS') { done = wrap(done, function(old, err) { if (err || options.length === 0) return old(err); - - var body = options.join(','); - return res.set('Allow', body).send(body); + sendOptionsResponse(res, options, old); }); } @@ -169,74 +170,104 @@ proto.handle = function(req, res, done) { ? null : err; - var layer = stack[idx++]; - + // remove added slash if (slashAdded) { req.url = req.url.substr(1); slashAdded = false; } + // restore altered req.url if (removed.length !== 0) { req.baseUrl = parentUrl; req.url = protohost + removed + req.url.substr(protohost.length); removed = ''; } - if (!layer) { + // no more matching layers + if (idx >= stack.length) { setImmediate(done, layerError); return; } - self.match_layer(layer, req, res, function (err, path) { - if (err || path === undefined) { + // get pathname of request + var path = getPathname(req); + + if (path == null) { + return done(layerError); + } + + // find next matching layer + var layer; + var match; + var route; + + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path); + route = layer.route; + + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match; + } + + if (match !== true) { + continue; + } + + if (!route) { + // process non-route handlers normally + continue; + } + + if (layerError) { + // routes do not match with a pending error + match = false; + continue; + } + + var method = req.method; + var has_method = route._handles_method(method); + + // build up automatic options response + if (!has_method && method === 'OPTIONS') { + appendMethods(options, route._options()); + } + + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + continue; + } + } + + // no match + if (match !== true) { + return done(layerError); + } + + // store route for dispatch on change + if (route) { + req.route = route; + } + + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; + + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { return next(layerError || err); } - // route object and not middleware - var route = layer.route; - - // if final route, then we support options if (route) { - // we don't run any routes with error first - if (layerError) { - return next(layerError); - } - - var method = req.method; - var has_method = route._handles_method(method); - - // build up automatic options response - if (!has_method && method === 'OPTIONS') { - options.push.apply(options, route._options()); - } - - // don't even bother - if (!has_method && method !== 'HEAD') { - return next(); - } - - // we can now dispatch to the route - req.route = route; + return layer.handle_request(req, res, next); } - // Capture one-time layer values - req.params = self.mergeParams - ? mergeParams(layer.params, parentParams) - : layer.params; - var layerPath = layer.path; - - // this should be done for the layer - self.process_params(layer, paramcalled, req, res, function (err) { - if (err) { - return next(layerError || err); - } - - if (route) { - return layer.handle_request(req, res, next); - } - - trim_prefix(layer, layerError, layerPath, path); - }); + trim_prefix(layer, layerError, layerPath, path); }); } @@ -273,29 +304,6 @@ proto.handle = function(req, res, done) { } }; -/** - * Match request to a layer. - * - * @api private - */ - -proto.match_layer = function match_layer(layer, req, res, done) { - var error = null; - var path; - - try { - path = parseUrl(req).pathname; - - if (!layer.match(path)) { - path = undefined; - } - } catch (err) { - error = err; - } - - done(error, path); -}; - /** * Process any parameters for the layer. * @@ -492,6 +500,25 @@ methods.concat('all').forEach(function(method){ }; }); +// append methods to a list of methods +function appendMethods(list, addition) { + for (var i = 0; i < addition.length; i++) { + var method = addition[i]; + if (list.indexOf(method) === -1) { + list.push(method); + } + } +} + +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; + } +} + // get type for error message function gettype(obj) { var type = typeof obj; @@ -505,6 +532,22 @@ function gettype(obj) { .replace(objectRegExp, '$1'); } +/** + * Match path to a layer. + * + * @param {Layer} layer + * @param {string} path + * @private + */ + +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; + } +} + // merge params with parent params function mergeParams(params, parent) { if (typeof parent !== 'object' || !parent) { @@ -561,6 +604,17 @@ function restore(fn, obj) { }; } +// send an OPTIONS response +function sendOptionsResponse(res, options, next) { + try { + var body = options.join(','); + res.set('Allow', body); + res.send(body); + } catch (err) { + next(err); + } +} + // wrap a function function wrap(old, fn) { return function proxy() { diff --git a/server/node_modules/express/lib/router/layer.js b/server/node_modules/express/lib/router/layer.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/lib/router/route.js b/server/node_modules/express/lib/router/route.js old mode 100755 new mode 100644 index 903d1a5e..6213b821 --- a/server/node_modules/express/lib/router/route.js +++ b/server/node_modules/express/lib/router/route.js @@ -52,10 +52,20 @@ Route.prototype._handles_method = function _handles_method(method) { * @api private */ -Route.prototype._options = function(){ - return Object.keys(this.methods).map(function(method) { - return method.toUpperCase(); - }); +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); + + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); + } + + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); + } + + return methods; }; /** diff --git a/server/node_modules/express/lib/utils.js b/server/node_modules/express/lib/utils.js old mode 100755 new mode 100644 index 9814527c..ce53ad8b --- a/server/node_modules/express/lib/utils.js +++ b/server/node_modules/express/lib/utils.js @@ -1,8 +1,17 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + /** * Module dependencies. + * @api private */ var contentDisposition = require('content-disposition'); +var contentType = require('content-type'); var deprecate = require('depd')('express'); var mime = require('send').mime; var basename = require('path').basename; @@ -10,7 +19,6 @@ var etag = require('etag'); var proxyaddr = require('proxy-addr'); var qs = require('qs'); var querystring = require('querystring'); -var typer = require('media-typer'); /** * Return strong ETag for `body`. @@ -258,21 +266,23 @@ exports.compileTrust = function(val) { * @api private */ -exports.setCharset = function(type, charset){ - if (!type || !charset) return type; +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } // parse type - var parsed = typer.parse(type); + var parsed = contentType.parse(type); // set charset parsed.parameters.charset = charset; // format type - return typer.format(parsed); + return contentType.format(parsed); }; /** - * Return new empty objet. + * Return new empty object. * * @return {Object} * @api private diff --git a/server/node_modules/express/lib/view.js b/server/node_modules/express/lib/view.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/accepts/HISTORY.md b/server/node_modules/express/node_modules/accepts/HISTORY.md old mode 100755 new mode 100644 index 05084815..86d7b9aa --- a/server/node_modules/express/node_modules/accepts/HISTORY.md +++ b/server/node_modules/express/node_modules/accepts/HISTORY.md @@ -1,3 +1,75 @@ +1.2.9 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - perf: fix deopt during mapping + +1.2.8 / 2015-06-07 +================== + + * deps: mime-types@~2.1.0 + - deps: mime-db@~1.13.0 + * perf: avoid argument reassignment & argument slice + * perf: avoid negotiator recursive construction + * perf: enable strict mode + * perf: remove unnecessary bitwise operator + +1.2.7 / 2015-05-10 +================== + + * deps: negotiator@0.5.3 + - Fix media type parameter matching to be case-insensitive + +1.2.6 / 2015-05-07 +================== + + * deps: mime-types@~2.0.11 + - deps: mime-db@~1.9.1 + * deps: negotiator@0.5.2 + - Fix comparing media types with quoted values + - Fix splitting media types with quoted commas + +1.2.5 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - deps: mime-db@~1.8.0 + +1.2.4 / 2015-02-14 +================== + + * Support Node.js 0.6 + * deps: mime-types@~2.0.9 + - deps: mime-db@~1.7.0 + * deps: negotiator@0.5.1 + - Fix preference sorting to be stable for long acceptable lists + +1.2.3 / 2015-01-31 +================== + + * deps: mime-types@~2.0.8 + - deps: mime-db@~1.6.0 + +1.2.2 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - deps: mime-db@~1.5.0 + +1.2.1 / 2014-12-30 +================== + + * deps: mime-types@~2.0.5 + - deps: mime-db@~1.3.1 + +1.2.0 / 2014-12-19 +================== + + * deps: negotiator@0.5.0 + - Fix list return order when large accepted list + - Fix missing identity encoding when q=0 exists + - Remove dynamic building of Negotiator class + 1.1.4 / 2014-12-10 ================== diff --git a/server/node_modules/express/node_modules/accepts/LICENSE b/server/node_modules/express/node_modules/accepts/LICENSE old mode 100755 new mode 100644 index f23dca8d..06166077 --- a/server/node_modules/express/node_modules/accepts/LICENSE +++ b/server/node_modules/express/node_modules/accepts/LICENSE @@ -1,6 +1,7 @@ (The MIT License) Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/server/node_modules/express/node_modules/accepts/README.md b/server/node_modules/express/node_modules/accepts/README.md old mode 100755 new mode 100644 index a9bc28af..ae36676f --- a/server/node_modules/express/node_modules/accepts/README.md +++ b/server/node_modules/express/node_modules/accepts/README.md @@ -6,89 +6,130 @@ [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] -Higher level content negotation based on [negotiator](https://github.com/federomero/negotiator). Extracted from [koa](https://github.com/koajs/koa) for general use. +Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). Extracted from [koa](https://www.npmjs.com/package/koa) for general use. -In addition to negotatior, it allows: +In addition to negotiator, it allows: - Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` as well as `('text/html', 'application/json')`. - Allows type shorthands such as `json`. - Returns `false` when no types match - Treats non-existent headers as `*` -## API +## Installation -### var accept = new Accepts(req) +```sh +npm install accepts +``` + +## API ```js var accepts = require('accepts') +``` -http.createServer(function (req, res) { +### accepts(req) + +Create a new `Accepts` object for the given `req`. + +#### .charset(charsets) + +Return the first accepted charset. If nothing in `charsets` is accepted, +then `false` is returned. + +#### .charsets() + +Return the charsets that the request accepts, in the order of the client's +preference (most preferred first). + +#### .encoding(encodings) + +Return the first accepted encoding. If nothing in `encodings` is accepted, +then `false` is returned. + +#### .encodings() + +Return the encodings that the request accepts, in the order of the client's +preference (most preferred first). + +#### .language(languages) + +Return the first accepted language. If nothing in `languages` is accepted, +then `false` is returned. + +#### .languages() + +Return the languages that the request accepts, in the order of the client's +preference (most preferred first). + +#### .type(types) + +Return the first accepted type (and it is returned as the same text as what +appears in the `types` array). If nothing in `types` is accepted, then `false` +is returned. + +The `types` array can contain full MIME types or file extensions. Any value +that is not a full MIME types is passed to `require('mime-types').lookup`. + +#### .types() + +Return the types that the request accepts, in the order of the client's +preference (most preferred first). + +## Examples + +### Simple type negotiation + +This simple example shows how to use `accepts` to return a different typed +respond body based on what the client wants to accept. The server lists it's +preferences in order and will get back the best match between the client and +server. + +```js +var accepts = require('accepts') +var http = require('http') + +function app(req, res) { var accept = accepts(req) -}) + + // the order of this list is significant; should be server preferred order + switch(accept.type(['json', 'html'])) { + case 'json': + res.setHeader('Content-Type', 'application/json') + res.write('{"hello":"world!"}') + break + case 'html': + res.setHeader('Content-Type', 'text/html') + res.write('hello, world!') + break + default: + // the fallback is text/plain, so no need to specify it above + res.setHeader('Content-Type', 'text/plain') + res.write('hello, world!') + break + } + + res.end() +} + +http.createServer(app).listen(3000) ``` -### accept\[property\]\(\) - -Returns all the explicitly accepted content property as an array in descending priority. - -- `accept.types()` -- `accept.encodings()` -- `accept.charsets()` -- `accept.languages()` - -They are also aliased in singular form such as `accept.type()`. `accept.languages()` is also aliased as `accept.langs()`, etc. - -Note: you should almost never do this in a real app as it defeats the purpose of content negotiation. - -Example: - -```js -// in Google Chrome -var encodings = accept.encodings() // -> ['sdch', 'gzip', 'deflate'] -``` - -Since you probably don't support `sdch`, you should just supply the encodings you support: - -```js -var encoding = accept.encodings('gzip', 'deflate') // -> 'gzip', probably -``` - -### accept\[property\]\(values, ...\) - -You can either have `values` be an array or have an argument list of values. - -If the client does not accept any `values`, `false` will be returned. -If the client accepts any `values`, the preferred `value` will be return. - -For `accept.types()`, shorthand mime types are allowed. - -Example: - -```js -// req.headers.accept = 'application/json' - -accept.types('json') // -> 'json' -accept.types('html', 'json') // -> 'json' -accept.types('html') // -> false - -// req.headers.accept = '' -// which is equivalent to `*` - -accept.types() // -> [], no explicit types -accept.types('text/html', 'text/json') // -> 'text/html', since it was first +You can test this out with the cURL program: +```sh +curl -I -H'Accept: text/html' http://localhost:3000/ ``` ## License [MIT](LICENSE) -[npm-image]: https://img.shields.io/npm/v/accepts.svg?style=flat +[npm-image]: https://img.shields.io/npm/v/accepts.svg [npm-url]: https://npmjs.org/package/accepts -[node-version-image]: https://img.shields.io/node/v/accepts.svg?style=flat +[node-version-image]: https://img.shields.io/node/v/accepts.svg [node-version-url]: http://nodejs.org/download/ -[travis-image]: https://img.shields.io/travis/jshttp/accepts.svg?style=flat +[travis-image]: https://img.shields.io/travis/jshttp/accepts/master.svg [travis-url]: https://travis-ci.org/jshttp/accepts -[coveralls-image]: https://img.shields.io/coveralls/jshttp/accepts.svg?style=flat +[coveralls-image]: https://img.shields.io/coveralls/jshttp/accepts/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/accepts -[downloads-image]: https://img.shields.io/npm/dm/accepts.svg?style=flat +[downloads-image]: https://img.shields.io/npm/dm/accepts.svg [downloads-url]: https://npmjs.org/package/accepts diff --git a/server/node_modules/express/node_modules/accepts/index.js b/server/node_modules/express/node_modules/accepts/index.js old mode 100755 new mode 100644 index 805e33ab..e80192ab --- a/server/node_modules/express/node_modules/accepts/index.js +++ b/server/node_modules/express/node_modules/accepts/index.js @@ -1,16 +1,40 @@ +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + var Negotiator = require('negotiator') var mime = require('mime-types') -var slice = [].slice +/** + * Module exports. + * @public + */ module.exports = Accepts +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ + function Accepts(req) { if (!(this instanceof Accepts)) return new Accepts(req) this.headers = req.headers - this.negotiator = Negotiator(req) + this.negotiator = new Negotiator(req) } /** @@ -49,19 +73,31 @@ function Accepts(req) { * this.types('html', 'json'); * // => "json" * - * @param {String|Array} type(s)... + * @param {String|Array} types... * @return {String|Array|Boolean} - * @api public + * @public */ Accepts.prototype.type = -Accepts.prototype.types = function (types) { - if (!Array.isArray(types)) types = slice.call(arguments); - var n = this.negotiator; - if (!types.length) return n.mediaTypes(); +Accepts.prototype.types = function (types_) { + var types = types_ + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] + } + } + + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } + if (!this.headers.accept) return types[0]; var mimes = types.map(extToMime); - var accepts = n.mediaTypes(mimes.filter(validMime)); + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)); var first = accepts[0]; if (!first) return false; return types[mimes.indexOf(first)]; @@ -75,17 +111,29 @@ Accepts.prototype.types = function (types) { * * ['gzip', 'deflate'] * - * @param {String|Array} encoding(s)... + * @param {String|Array} encodings... * @return {String|Array} - * @api public + * @public */ Accepts.prototype.encoding = -Accepts.prototype.encodings = function (encodings) { - if (!Array.isArray(encodings)) encodings = slice.call(arguments); - var n = this.negotiator; - if (!encodings.length) return n.encodings(); - return n.encodings(encodings)[0] || false; +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] + } + } + + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } + + return this.negotiator.encodings(encodings)[0] || false } /** @@ -96,18 +144,29 @@ Accepts.prototype.encodings = function (encodings) { * * ['utf-8', 'utf-7', 'iso-8859-1'] * - * @param {String|Array} charset(s)... + * @param {String|Array} charsets... * @return {String|Array} - * @api public + * @public */ Accepts.prototype.charset = -Accepts.prototype.charsets = function (charsets) { - if (!Array.isArray(charsets)) charsets = [].slice.call(arguments); - var n = this.negotiator; - if (!charsets.length) return n.charsets(); - if (!this.headers['accept-charset']) return charsets[0]; - return n.charsets(charsets)[0] || false; +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ + + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } + + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } + + return this.negotiator.charsets(charsets)[0] || false } /** @@ -118,20 +177,31 @@ Accepts.prototype.charsets = function (charsets) { * * ['es', 'pt', 'en'] * - * @param {String|Array} lang(s)... + * @param {String|Array} langs... * @return {Array|String} - * @api public + * @public */ Accepts.prototype.lang = Accepts.prototype.langs = Accepts.prototype.language = -Accepts.prototype.languages = function (langs) { - if (!Array.isArray(langs)) langs = slice.call(arguments); - var n = this.negotiator; - if (!langs.length) return n.languages(); - if (!this.headers['accept-language']) return langs[0]; - return n.languages(langs)[0] || false; +Accepts.prototype.languages = function (languages_) { + var languages = languages_ + + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } + } + + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() + } + + return this.negotiator.languages(languages)[0] || false } /** @@ -139,12 +209,13 @@ Accepts.prototype.languages = function (langs) { * * @param {String} type * @return {String} - * @api private + * @private */ function extToMime(type) { - if (~type.indexOf('/')) return type; - return mime.lookup(type); + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type } /** @@ -152,7 +223,7 @@ function extToMime(type) { * * @param {String} type * @return {String} - * @api private + * @private */ function validMime(type) { diff --git a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md old mode 100755 new mode 100644 index aa7cdf16..54689f91 --- a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md +++ b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md @@ -1,3 +1,47 @@ +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + 2.0.10 / 2015-03-13 =================== diff --git a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE old mode 100755 new mode 100644 index a7ae8ee9..06166077 --- a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE +++ b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE @@ -1,22 +1,23 @@ +(The MIT License) -The MIT License (MIT) +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson -Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: -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 above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md old mode 100755 new mode 100644 index 8fea7ff4..e26295d0 --- a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md +++ b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md @@ -42,10 +42,11 @@ All functions return `false` if input is invalid or not found. Lookup the content-type associated with a file. ```js -mime.lookup('json') // 'application/json' -mime.lookup('.md') // 'text/x-markdown' -mime.lookup('file.html') // 'text/html' -mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false mime.lookup('cats') // false ``` @@ -90,13 +91,13 @@ A map of extensions by content-type. [MIT](LICENSE) -[npm-image]: https://img.shields.io/npm/v/mime-types.svg?style=flat +[npm-image]: https://img.shields.io/npm/v/mime-types.svg [npm-url]: https://npmjs.org/package/mime-types -[node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat +[node-version-image]: https://img.shields.io/node/v/mime-types.svg [node-version-url]: http://nodejs.org/download/ -[travis-image]: https://img.shields.io/travis/jshttp/mime-types.svg?style=flat +[travis-image]: https://img.shields.io/travis/jshttp/mime-types/master.svg [travis-url]: https://travis-ci.org/jshttp/mime-types -[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-types.svg?style=flat +[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-types/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/mime-types -[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg?style=flat +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg [downloads-url]: https://npmjs.org/package/mime-types diff --git a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js old mode 100755 new mode 100644 index b46a202f..9edf72b7 --- a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js +++ b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js @@ -1,63 +1,188 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ var db = require('mime-db') +var extname = require('path').extname -// types[extension] = type -exports.types = Object.create(null) -// extensions[type] = [extensions] +/** + * Module variables. + * @private + */ + +var extractTypeRegExp = /^\s*([^;\s]*)(?:;|\s|$)/ +var textTypeRegExp = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) -Object.keys(db).forEach(function (name) { - var mime = db[name] - var exts = mime.extensions - if (!exts || !exts.length) return - exports.extensions[name] = exts - exts.forEach(function (ext) { - exports.types[ext] = name - }) -}) +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) -exports.lookup = function (string) { - if (!string || typeof string !== "string") return false - // remove any leading paths, though we should just use path.basename - string = string.replace(/.*[\.\/\\]/, '').toLowerCase() - if (!string) return false - return exports.types[string] || false -} +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ -exports.extension = function (type) { - if (!type || typeof type !== "string") return false - // to do: use media-typer - type = type.match(/^\s*([^;\s]*)(?:;|\s|$)/) - if (!type) return false - var exts = exports.extensions[type[1].toLowerCase()] - if (!exts || !exts.length) return false - return exts[0] -} +function charset(type) { + if (!type || typeof type !== 'string') { + return false + } -// type has to be an exact mime type -exports.charset = function (type) { - var mime = db[type] - if (mime && mime.charset) return mime.charset + // TODO: use media-typer + var match = extractTypeRegExp.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } // default text/* to utf-8 - if (/^text\//.test(type)) return 'UTF-8' + if (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } return false } -// backwards compatibility -exports.charsets = { - lookup: exports.charset +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType(str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime } -// to do: maybe use set-type module or something -exports.contentType = function (type) { - if (!type || typeof type !== "string") return false - if (!~type.indexOf('/')) type = exports.lookup(type) - if (!type) return false - if (!~type.indexOf('charset')) { - var charset = exports.charset(type) - if (charset) type += '; charset=' + charset.toLowerCase() +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension(type) { + if (!type || typeof type !== 'string') { + return false } - return type + + // TODO: use media-typer + var match = extractTypeRegExp.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup(path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps(extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType(type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' + && from > to || (from === to && types[extension].substr(0, 12) === 'application/')) { + // skip the remapping + return + } + } + + // set the extension -> mime + types[extension] = type + } + }) } diff --git a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md old mode 100755 new mode 100644 index 3c667481..415a8cf6 --- a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md +++ b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md @@ -1,3 +1,57 @@ +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + 1.8.0 / 2015-03-13 ================== diff --git a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md old mode 100755 new mode 100644 index 1dde2349..faf387f9 --- a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md +++ b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md @@ -13,6 +13,7 @@ It aggregates data from the following sources: - http://www.iana.org/assignments/media-types/media-types.xhtml - http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types ## Installation @@ -20,8 +21,12 @@ It aggregates data from the following sources: npm install mime-db ``` -If you're crazy enough to use this in the browser, -you can just grab the JSON file: +### Database Download + +If you're crazy enough to use this in the browser, you can just grab the +JSON file using [RawGit](https://rawgit.com/). It is recommended to replace +`master` with [a release tag](https://github.com/jshttp/mime-db/tags) as the +JSON format may change in the future. ``` https://cdn.rawgit.com/jshttp/mime-db/master/db.json @@ -45,6 +50,7 @@ Each mime type has the following properties: If not set, it's probably a custom media type. - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) - `.extensions[]` - known extensions associated with this mime type. - `.compressible` - whether a file of this type is can be gzipped. - `.charset` - the default charset associated with this type, if any. @@ -65,12 +71,12 @@ them with the IANA. The community registration procedure is outlined in [RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types registered with the IANA are automatically pulled into this library. -[npm-version-image]: https://img.shields.io/npm/v/mime-db.svg?style=flat -[npm-downloads-image]: https://img.shields.io/npm/dm/mime-db.svg?style=flat +[npm-version-image]: https://img.shields.io/npm/v/mime-db.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/mime-db.svg [npm-url]: https://npmjs.org/package/mime-db -[travis-image]: https://img.shields.io/travis/jshttp/mime-db.svg?style=flat +[travis-image]: https://img.shields.io/travis/jshttp/mime-db/master.svg [travis-url]: https://travis-ci.org/jshttp/mime-db -[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-db.svg?style=flat +[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-db/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master -[node-image]: https://img.shields.io/node/v/mime-db.svg?style=flat +[node-image]: https://img.shields.io/node/v/mime-db.svg [node-url]: http://nodejs.org/download/ diff --git a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json old mode 100755 new mode 100644 index f9f3515b..27cb4a1b --- a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json +++ b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json @@ -105,6 +105,10 @@ "application/batch-smtp": { "source": "iana" }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, "application/beep+xml": { "source": "iana" }, @@ -410,7 +414,7 @@ "application/java-archive": { "source": "apache", "compressible": false, - "extensions": ["jar"] + "extensions": ["jar","war","ear"] }, "application/java-serialized-object": { "source": "apache", @@ -513,6 +517,11 @@ "source": "iana", "extensions": ["mads"] }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, "application/marc": { "source": "iana", "extensions": ["mrc"] @@ -685,7 +694,7 @@ "application/octet-stream": { "source": "iana", "compressible": false, - "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","buffer"] + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] }, "application/oda": { "source": "iana", @@ -1307,6 +1316,9 @@ "application/vnd.balsamiq.bmml+xml": { "source": "iana" }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, "application/vnd.bekitzur-stech+json": { "source": "iana", "compressible": true @@ -2029,7 +2041,12 @@ "source": "iana" }, "application/vnd.hydrostatix.sof-data": { - "source": "iana" + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true }, "application/vnd.hzn-3d-crossword": { "source": "iana" @@ -2374,6 +2391,10 @@ "source": "iana", "extensions": ["mfm"] }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, "application/vnd.micrografx.flo": { "source": "iana", "extensions": ["flo"] @@ -2382,6 +2403,9 @@ "source": "iana", "extensions": ["igx"] }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, "application/vnd.miele+json": { "source": "iana", "compressible": true @@ -2713,7 +2737,8 @@ "extensions": ["ngdat"] }, "application/vnd.nokia.n-gage.symbian.install": { - "source": "iana" + "source": "iana", + "extensions": ["n-gage"] }, "application/vnd.nokia.ncd": { "source": "iana" @@ -4068,6 +4093,10 @@ "source": "apache", "extensions": ["bcpio"] }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, "application/x-bittorrent": { "source": "apache", "extensions": ["torrent"] @@ -4109,6 +4138,10 @@ "application/x-chrome-extension": { "extensions": ["crx"] }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, "application/x-compress": { "source": "apache" }, @@ -4263,6 +4296,10 @@ "source": "apache", "extensions": ["iso"] }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, "application/x-java-jnlp-file": { "source": "apache", "compressible": false, @@ -4283,6 +4320,10 @@ "source": "apache", "extensions": ["lzh","lha"] }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, "application/x-mie": { "source": "apache", "extensions": ["mie"] @@ -4366,10 +4407,22 @@ "source": "apache", "extensions": ["nc","cdf"] }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, "application/x-nzb": { "source": "apache", "extensions": ["nzb"] }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, "application/x-pkcs12": { "source": "apache", "compressible": false, @@ -4388,10 +4441,18 @@ "compressible": false, "extensions": ["rar"] }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, "application/x-research-info-systems": { "source": "apache", "extensions": ["ris"] }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, "application/x-sh": { "source": "apache", "compressible": true, @@ -4450,7 +4511,7 @@ }, "application/x-tcl": { "source": "apache", - "extensions": ["tcl"] + "extensions": ["tcl","tk"] }, "application/x-tex": { "source": "apache", @@ -4486,7 +4547,7 @@ }, "application/x-x509-ca-cert": { "source": "apache", - "extensions": ["der","crt"] + "extensions": ["der","crt","pem"] }, "application/x-xfig": { "source": "apache", @@ -4554,7 +4615,7 @@ "extensions": ["xhtml","xht"] }, "application/xhtml-voice+xml": { - "source": "iana" + "source": "apache" }, "application/xml": { "source": "iana", @@ -4855,7 +4916,7 @@ "extensions": ["oga","ogg","spx"] }, "audio/opus": { - "source": "apache" + "source": "iana" }, "audio/parityfec": { "source": "iana" @@ -5081,6 +5142,14 @@ "audio/vorbis-config": { "source": "iana" }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, "audio/webm": { "source": "apache", "compressible": false, @@ -5104,6 +5173,10 @@ "source": "apache", "extensions": ["flac"] }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, "audio/x-matroska": { "source": "apache", "extensions": ["mka"] @@ -5128,6 +5201,10 @@ "source": "apache", "extensions": ["rmp"] }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, "audio/x-tta": { "source": "apache" }, @@ -5355,6 +5432,9 @@ "source": "iana", "extensions": ["xif"] }, + "image/vnd.zbrush.pcx": { + "source": "iana" + }, "image/webp": { "source": "apache", "extensions": ["webp"] @@ -5380,10 +5460,19 @@ "compressible": true, "extensions": ["ico"] }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, "image/x-mrsid-image": { "source": "apache", "extensions": ["sid"] }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, "image/x-pcx": { "source": "apache", "extensions": ["pcx"] @@ -5647,7 +5736,7 @@ "compressible": true }, "text/coffeescript": { - "extensions": ["coffee"] + "extensions": ["coffee","litcoffee"] }, "text/css": { "source": "iana", @@ -5689,7 +5778,7 @@ "text/html": { "source": "iana", "compressible": true, - "extensions": ["html","htm"] + "extensions": ["html","htm","shtml"] }, "text/jade": { "extensions": ["jade"] @@ -5711,6 +5800,10 @@ "text/markdown": { "source": "iana" }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, "text/mizar": { "source": "iana" }, @@ -5755,7 +5848,9 @@ "extensions": ["rtx"] }, "text/rtf": { - "source": "iana" + "source": "iana", + "compressible": true, + "extensions": ["rtf"] }, "text/rtp-enc-aescm128": { "source": "iana" @@ -5916,6 +6011,7 @@ "extensions": ["c","cc","cxx","cpp","h","hh","dic"] }, "text/x-component": { + "source": "nginx", "extensions": ["htc"] }, "text/x-fortran": { @@ -5982,7 +6078,8 @@ }, "text/xml": { "source": "iana", - "compressible": true + "compressible": true, + "extensions": ["xml"] }, "text/xml-external-parsed-entity": { "source": "iana" @@ -5995,7 +6092,7 @@ }, "video/3gpp": { "source": "apache", - "extensions": ["3gp"] + "extensions": ["3gp","3gpp"] }, "video/3gpp-tt": { "source": "apache" diff --git a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json old mode 100755 new mode 100644 index 70438aca..44884d2a --- a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json +++ b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json @@ -1,7 +1,7 @@ { "name": "mime-db", "description": "Media Type Database", - "version": "1.8.0", + "version": "1.13.0", "contributors": [ { "name": "Douglas Christopher Wilson", @@ -30,17 +30,17 @@ ], "repository": { "type": "git", - "url": "https://github.com/jshttp/mime-db" + "url": "git://github.com/jshttp/mime-db" }, "devDependencies": { - "bluebird": "~2.9.14", - "co": "~4.4.0", - "cogent": "1", - "csv-parse": "0.0.9", + "bluebird": "2.9.27", + "co": "4.5.4", + "cogent": "1.0.1", + "csv-parse": "0.1.2", "gnode": "0.1.1", - "istanbul": "0.3.7", - "mocha": "~1.21.4", - "raw-body": "~1.3.3", + "istanbul": "0.3.14", + "mocha": "1.21.5", + "raw-body": "2.1.0", "stream-to-array": "2" }, "files": [ @@ -55,39 +55,21 @@ }, "scripts": { "build": "node scripts/build", - "fetch": "gnode scripts/extensions && gnode scripts/types", + "fetch": "gnode scripts/fetch-apache && gnode scripts/fetch-iana && gnode scripts/fetch-nginx", "test": "mocha --reporter spec --bail --check-leaks test/", "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", "update": "npm run fetch && npm run build" }, - "gitHead": "cd5730a475ff03d2ef49fc571d5510a548b63494", + "readme": "# mime-db\n\n[![NPM Version][npm-version-image]][npm-url]\n[![NPM Downloads][npm-downloads-image]][npm-url]\n[![Node.js Version][node-image]][node-url]\n[![Build Status][travis-image]][travis-url]\n[![Coverage Status][coveralls-image]][coveralls-url]\n\nThis is a database of all mime types.\nIt consists of a single, public JSON file and does not include any logic,\nallowing it to remain as un-opinionated as possible with an API.\nIt aggregates data from the following sources:\n\n- http://www.iana.org/assignments/media-types/media-types.xhtml\n- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types\n- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types\n\n## Installation\n\n```bash\nnpm install mime-db\n```\n\n### Database Download\n\nIf you're crazy enough to use this in the browser, you can just grab the\nJSON file using [RawGit](https://rawgit.com/). It is recommended to replace\n`master` with [a release tag](https://github.com/jshttp/mime-db/tags) as the\nJSON format may change in the future.\n\n```\nhttps://cdn.rawgit.com/jshttp/mime-db/master/db.json\n```\n\n## Usage\n\n```js\nvar db = require('mime-db');\n\n// grab data on .js files\nvar data = db['application/javascript'];\n```\n\n## Data Structure\n\nThe JSON file is a map lookup for lowercased mime types.\nEach mime type has the following properties:\n\n- `.source` - where the mime type is defined.\n If not set, it's probably a custom media type.\n - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types)\n - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml)\n - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types)\n- `.extensions[]` - known extensions associated with this mime type.\n- `.compressible` - whether a file of this type is can be gzipped.\n- `.charset` - the default charset associated with this type, if any.\n\nIf unknown, every property could be `undefined`.\n\n## Contributing\n\nTo edit the database, only make PRs against `src/custom.json` or\n`src/custom-suffix.json`.\n\nTo update the build, run `npm run update`.\n\n## Adding Custom Media Types\n\nThe best way to get new media types included in this library is to register\nthem with the IANA. The community registration procedure is outlined in\n[RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types\nregistered with the IANA are automatically pulled into this library.\n\n[npm-version-image]: https://img.shields.io/npm/v/mime-db.svg\n[npm-downloads-image]: https://img.shields.io/npm/dm/mime-db.svg\n[npm-url]: https://npmjs.org/package/mime-db\n[travis-image]: https://img.shields.io/travis/jshttp/mime-db/master.svg\n[travis-url]: https://travis-ci.org/jshttp/mime-db\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-db/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master\n[node-image]: https://img.shields.io/node/v/mime-db.svg\n[node-url]: http://nodejs.org/download/\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/mime-db/issues" }, - "homepage": "https://github.com/jshttp/mime-db", - "_id": "mime-db@1.8.0", - "_shasum": "82a9b385f22b0f5954dec4d445faba0722c4ad25", - "_from": "mime-db@~1.8.0", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], + "_id": "mime-db@1.13.0", "dist": { - "shasum": "82a9b385f22b0f5954dec4d445faba0722c4ad25", - "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.8.0.tgz" + "shasum": "b6b90fbdab177a601068c884408bea3118e3f407" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.8.0.tgz" + "_from": "mime-db@~1.13.0", + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.13.0.tgz" } diff --git a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json old mode 100755 new mode 100644 index 5fe0d5d1..7605a8b7 --- a/server/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json +++ b/server/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json @@ -1,7 +1,7 @@ { "name": "mime-types", "description": "The ultimate javascript content-type utility.", - "version": "2.0.10", + "version": "2.1.1", "contributors": [ { "name": "Douglas Christopher Wilson", @@ -25,13 +25,13 @@ ], "repository": { "type": "git", - "url": "https://github.com/jshttp/mime-types" + "url": "git://github.com/jshttp/mime-types" }, "dependencies": { - "mime-db": "~1.8.0" + "mime-db": "~1.13.0" }, "devDependencies": { - "istanbul": "0.3.7", + "istanbul": "0.3.14", "mocha": "~1.21.5" }, "files": [ @@ -47,37 +47,15 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/test.js", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot test/test.js" }, - "gitHead": "9d4533a2b3a68af48a7f3ded9f8f525648e7bcc1", + "readme": "# mime-types\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nThe ultimate javascript content-type utility.\n\nSimilar to [node-mime](https://github.com/broofa/node-mime), except:\n\n- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`,\n so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`.\n- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`.\n- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db)\n- No `.define()` functionality\n\nOtherwise, the API is compatible.\n\n## Install\n\n```sh\n$ npm install mime-types\n```\n\n## Adding Types\n\nAll mime types are based on [mime-db](https://github.com/jshttp/mime-db),\nso open a PR there if you'd like to add mime types.\n\n## API\n\n```js\nvar mime = require('mime-types')\n```\n\nAll functions return `false` if input is invalid or not found.\n\n### mime.lookup(path)\n\nLookup the content-type associated with a file.\n\n```js\nmime.lookup('json') // 'application/json'\nmime.lookup('.md') // 'text/x-markdown'\nmime.lookup('file.html') // 'text/html'\nmime.lookup('folder/file.js') // 'application/javascript'\nmime.lookup('folder/.htaccess') // false\n\nmime.lookup('cats') // false\n```\n\n### mime.contentType(type)\n\nCreate a full content-type header given a content-type or extension.\n\n```js\nmime.contentType('markdown') // 'text/x-markdown; charset=utf-8'\nmime.contentType('file.json') // 'application/json; charset=utf-8'\n\n// from a full path\nmime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8'\n```\n\n### mime.extension(type)\n\nGet the default extension for a content-type.\n\n```js\nmime.extension('application/octet-stream') // 'bin'\n```\n\n### mime.charset(type)\n\nLookup the implied default charset of a content-type.\n\n```js\nmime.charset('text/x-markdown') // 'UTF-8'\n```\n\n### var type = mime.types[extension]\n\nA map of content-types by extension.\n\n### [extensions...] = mime.extensions[type]\n\nA map of extensions by content-type.\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/mime-types.svg\n[npm-url]: https://npmjs.org/package/mime-types\n[node-version-image]: https://img.shields.io/node/v/mime-types.svg\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/mime-types/master.svg\n[travis-url]: https://travis-ci.org/jshttp/mime-types\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-types/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/mime-types\n[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg\n[downloads-url]: https://npmjs.org/package/mime-types\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/mime-types/issues" }, - "homepage": "https://github.com/jshttp/mime-types", - "_id": "mime-types@2.0.10", - "_shasum": "eacd81bb73cab2a77447549a078d4f2018c67b4d", - "_from": "mime-types@~2.0.4", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "fishrock123", - "email": "fishrock123@rocketmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], + "_id": "mime-types@2.1.1", "dist": { - "shasum": "eacd81bb73cab2a77447549a078d4f2018c67b4d", - "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.0.10.tgz" + "shasum": "07341942622db6e106a6f7f83922c1fdc54051cc" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.0.10.tgz" + "_from": "mime-types@~2.1.1", + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.1.tgz" } diff --git a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE old mode 100755 new mode 100644 index 692b5341..ea6b9e2e --- a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE +++ b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE @@ -1,7 +1,8 @@ (The MIT License) -Copyright (c) 2012 Federico Romero +Copyright (c) 2012-2014 Federico Romero Copyright (c) 2012-2014 Isaac Z. Schlueter +Copyright (c) 2014-2015 Douglas Christopher Wilson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md old mode 100755 new mode 100644 index 2461eb1e..ef507faa --- a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md +++ b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md @@ -44,13 +44,22 @@ You can check a working example at `examples/accept.js`. #### Methods -##### mediaTypes(availableMediaTypes): +##### mediaType() -Returns an array of preferred media types ordered by priority from a list of available media types. +Returns the most preferred media type from the client. -##### mediaType(availableMediaType): +##### mediaType(availableMediaType) -Returns the top preferred media type from a list of available media types. +Returns the most preferred media type from a list of available media types. + +##### mediaTypes() + +Returns an array of preferred media types ordered by the client preference. + +##### mediaTypes(availableMediaTypes) + +Returns an array of preferred media types ordered by priority from a list of +available media types. ### Accept-Language Negotiation @@ -75,13 +84,22 @@ You can check a working example at `examples/language.js`. #### Methods -##### languages(availableLanguages): +##### language() -Returns an array of preferred languages ordered by priority from a list of available languages. +Returns the most preferred language from the client. -##### language(availableLanguages): +##### language(availableLanguages) -Returns the top preferred language from a list of available languages. +Returns the most preferred language from a list of available languages. + +##### languages() + +Returns an array of preferred languages ordered by the client preference. + +##### languages(availableLanguages) + +Returns an array of preferred languages ordered by priority from a list of +available languages. ### Accept-Charset Negotiation @@ -106,13 +124,22 @@ You can check a working example at `examples/charset.js`. #### Methods -##### charsets(availableCharsets): +##### charset() -Returns an array of preferred charsets ordered by priority from a list of available charsets. +Returns the most preferred charset from the client. -##### charset(availableCharsets): +##### charset(availableCharsets) -Returns the top preferred charset from a list of available charsets. +Returns the most preferred charset from a list of available charsets. + +##### charsets() + +Returns an array of preferred charsets ordered by the client preference. + +##### charsets(availableCharsets) + +Returns an array of preferred charsets ordered by priority from a list of +available charsets. ### Accept-Encoding Negotiation @@ -137,25 +164,40 @@ You can check a working example at `examples/encoding.js`. #### Methods -##### encodings(availableEncodings): +##### encoding() -Returns an array of preferred encodings ordered by priority from a list of available encodings. +Returns the most preferred encoding from the client. -##### encoding(availableEncodings): +##### encoding(availableEncodings) -Returns the top preferred encoding from a list of available encodings. +Returns the most preferred encoding from a list of available encodings. + +##### encodings() + +Returns an array of preferred encodings ordered by the client preference. + +##### encodings(availableEncodings) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings. + +## See Also + +The [accepts](https://npmjs.org/package/accepts#readme) module builds on +this module and provides an alternative interface, mime type validation, +and more. ## License [MIT](LICENSE) -[npm-image]: https://img.shields.io/npm/v/negotiator.svg?style=flat +[npm-image]: https://img.shields.io/npm/v/negotiator.svg [npm-url]: https://npmjs.org/package/negotiator -[node-version-image]: https://img.shields.io/node/v/negotiator.svg?style=flat +[node-version-image]: https://img.shields.io/node/v/negotiator.svg [node-version-url]: http://nodejs.org/download/ -[travis-image]: https://img.shields.io/travis/jshttp/negotiator.svg?style=flat +[travis-image]: https://img.shields.io/travis/jshttp/negotiator/master.svg [travis-url]: https://travis-ci.org/jshttp/negotiator -[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator.svg?style=flat +[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master -[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg?style=flat +[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg [downloads-url]: https://npmjs.org/package/negotiator diff --git a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js old mode 100755 new mode 100644 index 58da58fc..7abd17c1 --- a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js +++ b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js @@ -2,11 +2,20 @@ module.exports = preferredCharsets; preferredCharsets.preferredCharsets = preferredCharsets; function parseAcceptCharset(accept) { - return accept.split(',').map(function(e, i) { - return parseCharset(e.trim(), i); - }).filter(function(e) { - return e; - }); + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var charset = parseCharset(accepts[i].trim(), i); + + if (charset) { + accepts[j++] = charset; + } + } + + // trim accepts + accepts.length = j; + + return accepts; } function parseCharset(s, i) { @@ -33,19 +42,21 @@ function parseCharset(s, i) { }; } -function getCharsetPriority(charset, accepted) { - return (accepted.map(function(a) { - return specify(charset, a); - }).filter(Boolean).sort(function (a, b) { - if(a.s == b.s) { - return a.q > b.q ? -1 : 1; - } else { - return a.s > b.s ? -1 : 1; +function getCharsetPriority(charset, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(charset, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; } - })[0] || {s: 0, q:0}); + } + + return priority; } -function specify(charset, spec) { +function specify(charset, spec, index) { var s = 0; if(spec.charset.toLowerCase() === charset.toLowerCase()){ s |= 1; @@ -54,34 +65,38 @@ function specify(charset, spec) { } return { - s: s, + i: index, + o: spec.i, q: spec.q, + s: s } } function preferredCharsets(accept, provided) { // RFC 2616 sec 14.2: no header = * - accept = parseAcceptCharset(accept === undefined ? '*' : accept || ''); - if (provided) { - return provided.map(function(type) { - return [type, getCharsetPriority(type, accept)]; - }).filter(function(pair) { - return pair[1].q > 0; - }).sort(function(a, b) { - var pa = a[1]; - var pb = b[1]; - return (pb.q - pa.q) || (pb.s - pa.s) || (pa.i - pb.i); - }).map(function(pair) { - return pair[0]; - }); - } else { - return accept.sort(function (a, b) { - // revsort - return (b.q - a.q) || (a.i - b.i); - }).filter(function(type) { - return type.q > 0; - }).map(function(type) { - return type.charset; + var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all charsets + return accepts.filter(isQuality).sort(compareSpecs).map(function getCharset(spec) { + return spec.charset; }); } + + var priorities = provided.map(function getPriority(type, index) { + return getCharsetPriority(type, accepts, index); + }); + + // sorted list of accepted charsets + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +function isQuality(spec) { + return spec.q > 0; } diff --git a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js old mode 100755 new mode 100644 index 4b8acc1a..7fed6733 --- a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js +++ b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js @@ -2,41 +2,36 @@ module.exports = preferredEncodings; preferredEncodings.preferredEncodings = preferredEncodings; function parseAcceptEncoding(accept) { - var acceptableEncodings; + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; - if (accept) { - acceptableEncodings = accept.split(',').map(function(e, i) { - return parseEncoding(e.trim(), i); - }); - } else { - acceptableEncodings = []; + for (var i = 0, j = 0; i < accepts.length; i++) { + var encoding = parseEncoding(accepts[i].trim(), i); + + if (encoding) { + accepts[j++] = encoding; + hasIdentity = hasIdentity || specify('identity', encoding); + minQuality = Math.min(minQuality, encoding.q || 1); + } } - if (!acceptableEncodings.some(function(e) { - return e && specify('identity', e); - })) { + if (!hasIdentity) { /* * If identity doesn't explicitly appear in the accept-encoding header, * it's added to the list of acceptable encoding with the lowest q - * */ - var lowestQ = 1; - - for(var i = 0; i < acceptableEncodings.length; i++){ - var e = acceptableEncodings[i]; - if(e && e.q < lowestQ){ - lowestQ = e.q; - } - } - acceptableEncodings.push({ + accepts[j++] = { encoding: 'identity', - q: lowestQ / 2, - }); + q: minQuality, + i: i + }; } - return acceptableEncodings.filter(function(e) { - return e; - }); + // trim accepts + accepts.length = j; + + return accepts; } function parseEncoding(s, i) { @@ -64,19 +59,21 @@ function parseEncoding(s, i) { }; } -function getEncodingPriority(encoding, accepted) { - return (accepted.map(function(a) { - return specify(encoding, a); - }).filter(Boolean).sort(function (a, b) { - if(a.s == b.s) { - return a.q > b.q ? -1 : 1; - } else { - return a.s > b.s ? -1 : 1; +function getEncodingPriority(encoding, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(encoding, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; } - })[0] || {s: 0, q: 0}); + } + + return priority; } -function specify(encoding, spec) { +function specify(encoding, spec, index) { var s = 0; if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ s |= 1; @@ -85,33 +82,37 @@ function specify(encoding, spec) { } return { - s: s, + i: index, + o: spec.i, q: spec.q, + s: s } }; function preferredEncodings(accept, provided) { - accept = parseAcceptEncoding(accept || ''); - if (provided) { - return provided.map(function(type) { - return [type, getEncodingPriority(type, accept)]; - }).filter(function(pair) { - return pair[1].q > 0; - }).sort(function(a, b) { - var pa = a[1]; - var pb = b[1]; - return (pb.q - pa.q) || (pb.s - pa.s) || (pa.i - pb.i); - }).map(function(pair) { - return pair[0]; - }); - } else { - return accept.sort(function (a, b) { - // revsort - return (b.q - a.q) || (a.i - b.i); - }).filter(function(type){ - return type.q > 0; - }).map(function(type) { - return type.encoding; + var accepts = parseAcceptEncoding(accept || ''); + + if (!provided) { + // sorted list of all encodings + return accepts.filter(isQuality).sort(compareSpecs).map(function getEncoding(spec) { + return spec.encoding; }); } + + var priorities = provided.map(function getPriority(type, index) { + return getEncodingPriority(type, accepts, index); + }); + + // sorted list of accepted encodings + return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +function isQuality(spec) { + return spec.q > 0; } diff --git a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js old mode 100755 new mode 100644 index 8fc63dfe..ed9e1ec0 --- a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js +++ b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js @@ -2,11 +2,20 @@ module.exports = preferredLanguages; preferredLanguages.preferredLanguages = preferredLanguages; function parseAcceptLanguage(accept) { - return accept.split(',').map(function(e, i) { - return parseLanguage(e.trim(), i); - }).filter(function(e) { - return e; - }); + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var langauge = parseLanguage(accepts[i].trim(), i); + + if (langauge) { + accepts[j++] = langauge; + } + } + + // trim accepts + accepts.length = j; + + return accepts; } function parseLanguage(s, i) { @@ -37,19 +46,21 @@ function parseLanguage(s, i) { }; } -function getLanguagePriority(language, accepted) { - return (accepted.map(function(a){ - return specify(language, a); - }).filter(Boolean).sort(function (a, b) { - if(a.s == b.s) { - return a.q > b.q ? -1 : 1; - } else { - return a.s > b.s ? -1 : 1; +function getLanguagePriority(language, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(language, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; } - })[0] || {s: 0, q: 0}); + } + + return priority; } -function specify(language, spec) { +function specify(language, spec, index) { var p = parseLanguage(language) if (!p) return null; var s = 0; @@ -64,37 +75,38 @@ function specify(language, spec) { } return { - s: s, + i: index, + o: spec.i, q: spec.q, + s: s } }; function preferredLanguages(accept, provided) { // RFC 2616 sec 14.4: no header = * - accept = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); - if (provided) { + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); - var ret = provided.map(function(type) { - return [type, getLanguagePriority(type, accept)]; - }).filter(function(pair) { - return pair[1].q > 0; - }).sort(function(a, b) { - var pa = a[1]; - var pb = b[1]; - return (pb.q - pa.q) || (pb.s - pa.s) || (pa.i - pb.i); - }).map(function(pair) { - return pair[0]; - }); - return ret; - - } else { - return accept.sort(function (a, b) { - // revsort - return (b.q - a.q) || (a.i - b.i); - }).filter(function(type) { - return type.q > 0; - }).map(function(type) { - return type.full; + if (!provided) { + // sorted list of all languages + return accepts.filter(isQuality).sort(compareSpecs).map(function getLanguage(spec) { + return spec.full; }); } + + var priorities = provided.map(function getPriority(type, index) { + return getLanguagePriority(type, accepts, index); + }); + + // sorted list of accepted languages + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +function isQuality(spec) { + return spec.q > 0; } diff --git a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js old mode 100755 new mode 100644 index e413cad4..4170c258 --- a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js +++ b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js @@ -1,12 +1,29 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + module.exports = preferredMediaTypes; preferredMediaTypes.preferredMediaTypes = preferredMediaTypes; function parseAccept(accept) { - return accept.split(',').map(function(e, i) { - return parseMediaType(e.trim(), i); - }).filter(function(e) { - return e; - }); + var accepts = splitMediaTypes(accept); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var mediaType = parseMediaType(accepts[i].trim(), i); + + if (mediaType) { + accepts[j++] = mediaType; + } + } + + // trim accepts + accepts.length = j; + + return accepts; }; function parseMediaType(s, i) { @@ -23,8 +40,14 @@ function parseMediaType(s, i) { params = match[3].split(';').map(function(s) { return s.trim().split('='); }).reduce(function (set, p) { - set[p[0]] = p[1]; - return set + var name = p[0].toLowerCase(); + var value = p[1]; + + set[name] = value && value[0] === '"' && value[value.length - 1] === '"' + ? value.substr(1, value.length - 2) + : value; + + return set; }, params); if (params.q != null) { @@ -43,19 +66,21 @@ function parseMediaType(s, i) { }; } -function getMediaTypePriority(type, accepted) { - return (accepted.map(function(a) { - return specify(type, a); - }).filter(Boolean).sort(function (a, b) { - if(a.s == b.s) { - return a.q > b.q ? -1 : 1; - } else { - return a.s > b.s ? -1 : 1; +function getMediaTypePriority(type, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(type, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; } - })[0] || {s: 0, q: 0}); + } + + return priority; } -function specify(type, spec) { +function specify(type, spec, index) { var p = parseMediaType(type); var s = 0; @@ -87,6 +112,8 @@ function specify(type, spec) { } return { + i: index, + o: spec.i, q: spec.q, s: s, } @@ -95,28 +122,58 @@ function specify(type, spec) { function preferredMediaTypes(accept, provided) { // RFC 2616 sec 14.2: no header = */* - accept = parseAccept(accept === undefined ? '*/*' : accept || ''); - if (provided) { - return provided.map(function(type) { - return [type, getMediaTypePriority(type, accept)]; - }).filter(function(pair) { - return pair[1].q > 0; - }).sort(function(a, b) { - var pa = a[1]; - var pb = b[1]; - return (pb.q - pa.q) || (pb.s - pa.s) || (pa.i - pb.i); - }).map(function(pair) { - return pair[0]; - }); + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); - } else { - return accept.sort(function (a, b) { - // revsort - return (b.q - a.q) || (a.i - b.i); - }).filter(function(type) { - return type.q > 0; - }).map(function(type) { - return type.full; + if (!provided) { + // sorted list of all types + return accepts.filter(isQuality).sort(compareSpecs).map(function getType(spec) { + return spec.full; }); } + + var priorities = provided.map(function getPriority(type, index) { + return getMediaTypePriority(type, accepts, index); + }); + + // sorted list of accepted types + return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +function isQuality(spec) { + return spec.q > 0; +} + +function quoteCount(string) { + var count = 0; + var index = 0; + + while ((index = string.indexOf('"', index)) !== -1) { + count++; + index++; + } + + return count; +} + +function splitMediaTypes(accept) { + var accepts = accept.split(','); + + for (var i = 1, j = 0; i < accepts.length; i++) { + if (quoteCount(accepts[j]) % 2 == 0) { + accepts[++j] = accepts[i]; + } else { + accepts[j] += ',' + accepts[i]; + } + } + + // trim accepts + accepts.length = j + 1; + + return accepts; } diff --git a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/negotiator.js b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/negotiator.js deleted file mode 100755 index ba0c48b9..00000000 --- a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/negotiator.js +++ /dev/null @@ -1,37 +0,0 @@ -module.exports = Negotiator; -Negotiator.Negotiator = Negotiator; - -function Negotiator(request) { - if (!(this instanceof Negotiator)) return new Negotiator(request); - this.request = request; -} - -var set = { charset: 'accept-charset', - encoding: 'accept-encoding', - language: 'accept-language', - mediaType: 'accept' }; - - -function capitalize(string){ - return string.charAt(0).toUpperCase() + string.slice(1); -} - -Object.keys(set).forEach(function (k) { - var header = set[k], - method = require('./'+k+'.js'), - singular = k, - plural = k + 's'; - - Negotiator.prototype[plural] = function (available) { - return method(this.request.headers[header], available); - }; - - Negotiator.prototype[singular] = function(available) { - var set = this[plural](available); - if (set) return set[0]; - }; - - // Keep preferred* methods for legacy compatibility - Negotiator.prototype['preferred'+capitalize(plural)] = Negotiator.prototype[plural]; - Negotiator.prototype['preferred'+capitalize(singular)] = Negotiator.prototype[singular]; -}) diff --git a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json old mode 100755 new mode 100644 index 10f8c8e6..7a2cebb1 --- a/server/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json +++ b/server/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json @@ -1,22 +1,23 @@ { "name": "negotiator", "description": "HTTP content negotiation", - "version": "0.4.9", - "author": { - "name": "Federico Romero", - "email": "federico.romero@outboxlabs.com" - }, + "version": "0.5.3", "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Federico Romero", + "email": "federico.romero@outboxlabs.com" + }, { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" } ], - "repository": { - "type": "git", - "url": "https://github.com/jshttp/negotiator" - }, + "license": "MIT", "keywords": [ "http", "content negotiation", @@ -25,54 +26,34 @@ "accept-encoding", "accept-charset" ], - "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/jshttp/negotiator" + }, "devDependencies": { - "istanbul": "~0.3.2", - "nodeunit": "0.8.x" - }, - "scripts": { - "test": "nodeunit test", - "test-cov": "istanbul cover ./node_modules/nodeunit/bin/nodeunit test" + "istanbul": "0.3.9", + "mocha": "~1.21.5" }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], "engines": { "node": ">= 0.6" }, - "main": "lib/negotiator.js", - "files": [ - "lib", - "LICENSE" - ], - "gitHead": "1e90abd710b662db80f1ea244e647cce3bd74504", + "scripts": { + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "readme": "# negotiator\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nAn HTTP content negotiator for Node.js\n\n## Installation\n\n```sh\n$ npm install negotiator\n```\n\n## API\n\n```js\nvar Negotiator = require('negotiator')\n```\n\n### Accept Negotiation\n\n```js\navailableMediaTypes = ['text/html', 'text/plain', 'application/json']\n\n// The negotiator constructor receives a request object\nnegotiator = new Negotiator(request)\n\n// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8'\n\nnegotiator.mediaTypes()\n// -> ['text/html', 'image/jpeg', 'application/*']\n\nnegotiator.mediaTypes(availableMediaTypes)\n// -> ['text/html', 'application/json']\n\nnegotiator.mediaType(availableMediaTypes)\n// -> 'text/html'\n```\n\nYou can check a working example at `examples/accept.js`.\n\n#### Methods\n\n##### mediaType()\n\nReturns the most preferred media type from the client.\n\n##### mediaType(availableMediaType)\n\nReturns the most preferred media type from a list of available media types.\n\n##### mediaTypes()\n\nReturns an array of preferred media types ordered by the client preference.\n\n##### mediaTypes(availableMediaTypes)\n\nReturns an array of preferred media types ordered by priority from a list of\navailable media types.\n\n### Accept-Language Negotiation\n\n```js\nnegotiator = new Negotiator(request)\n\navailableLanguages = 'en', 'es', 'fr'\n\n// Let's say Accept-Language header is 'en;q=0.8, es, pt'\n\nnegotiator.languages()\n// -> ['es', 'pt', 'en']\n\nnegotiator.languages(availableLanguages)\n// -> ['es', 'en']\n\nlanguage = negotiator.language(availableLanguages)\n// -> 'es'\n```\n\nYou can check a working example at `examples/language.js`.\n\n#### Methods\n\n##### language()\n\nReturns the most preferred language from the client.\n\n##### language(availableLanguages)\n\nReturns the most preferred language from a list of available languages.\n\n##### languages()\n\nReturns an array of preferred languages ordered by the client preference.\n\n##### languages(availableLanguages)\n\nReturns an array of preferred languages ordered by priority from a list of\navailable languages.\n\n### Accept-Charset Negotiation\n\n```js\navailableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5']\n\nnegotiator = new Negotiator(request)\n\n// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2'\n\nnegotiator.charsets()\n// -> ['utf-8', 'iso-8859-1', 'utf-7']\n\nnegotiator.charsets(availableCharsets)\n// -> ['utf-8', 'iso-8859-1']\n\nnegotiator.charset(availableCharsets)\n// -> 'utf-8'\n```\n\nYou can check a working example at `examples/charset.js`.\n\n#### Methods\n\n##### charset()\n\nReturns the most preferred charset from the client.\n\n##### charset(availableCharsets)\n\nReturns the most preferred charset from a list of available charsets.\n\n##### charsets()\n\nReturns an array of preferred charsets ordered by the client preference.\n\n##### charsets(availableCharsets)\n\nReturns an array of preferred charsets ordered by priority from a list of\navailable charsets.\n\n### Accept-Encoding Negotiation\n\n```js\navailableEncodings = ['identity', 'gzip']\n\nnegotiator = new Negotiator(request)\n\n// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5'\n\nnegotiator.encodings()\n// -> ['gzip', 'identity', 'compress']\n\nnegotiator.encodings(availableEncodings)\n// -> ['gzip', 'identity']\n\nnegotiator.encoding(availableEncodings)\n// -> 'gzip'\n```\n\nYou can check a working example at `examples/encoding.js`.\n\n#### Methods\n\n##### encoding()\n\nReturns the most preferred encoding from the client.\n\n##### encoding(availableEncodings)\n\nReturns the most preferred encoding from a list of available encodings.\n\n##### encodings()\n\nReturns an array of preferred encodings ordered by the client preference.\n\n##### encodings(availableEncodings)\n\nReturns an array of preferred encodings ordered by priority from a list of\navailable encodings.\n\n## See Also\n\nThe [accepts](https://npmjs.org/package/accepts#readme) module builds on\nthis module and provides an alternative interface, mime type validation,\nand more.\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/negotiator.svg\n[npm-url]: https://npmjs.org/package/negotiator\n[node-version-image]: https://img.shields.io/node/v/negotiator.svg\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/negotiator/master.svg\n[travis-url]: https://travis-ci.org/jshttp/negotiator\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg\n[downloads-url]: https://npmjs.org/package/negotiator\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/negotiator/issues" }, - "homepage": "https://github.com/jshttp/negotiator", - "_id": "negotiator@0.4.9", - "_shasum": "92e46b6db53c7e421ed64a2bc94f08be7630df3f", - "_from": "negotiator@0.4.9", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "federomero", - "email": "federomero@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - } - ], - "dist": { - "shasum": "92e46b6db53c7e421ed64a2bc94f08be7630df3f", - "tarball": "http://registry.npmjs.org/negotiator/-/negotiator-0.4.9.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.4.9.tgz" + "_id": "negotiator@0.5.3", + "_from": "negotiator@0.5.3" } diff --git a/server/node_modules/express/node_modules/accepts/package.json b/server/node_modules/express/node_modules/accepts/package.json old mode 100755 new mode 100644 index d60bd5ed..2aa6509d --- a/server/node_modules/express/node_modules/accepts/package.json +++ b/server/node_modules/express/node_modules/accepts/package.json @@ -1,24 +1,30 @@ { "name": "accepts", "description": "Higher-level content negotiation", - "version": "1.1.4", - "author": { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, + "version": "1.2.9", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/jshttp/accepts" + "url": "git://github.com/jshttp/accepts" }, "dependencies": { - "mime-types": "~2.0.4", - "negotiator": "0.4.9" + "mime-types": "~2.1.1", + "negotiator": "0.5.3" }, "devDependencies": { - "istanbul": "~0.3.4", - "mocha": "~2.0.1" + "istanbul": "0.3.14", + "mocha": "~1.21.5" }, "files": [ "LICENSE", @@ -26,7 +32,7 @@ "index.js" ], "engines": { - "node": ">= 0.8" + "node": ">= 0.6" }, "scripts": { "test": "mocha --reporter spec --check-leaks --bail test/", @@ -39,53 +45,15 @@ "accept", "accepts" ], - "gitHead": "df66414d80f096627b28f137127fce0a851d7900", + "readme": "# accepts\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nHigher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). Extracted from [koa](https://www.npmjs.com/package/koa) for general use.\n\nIn addition to negotiator, it allows:\n\n- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` as well as `('text/html', 'application/json')`.\n- Allows type shorthands such as `json`.\n- Returns `false` when no types match\n- Treats non-existent headers as `*`\n\n## Installation\n\n```sh\nnpm install accepts\n```\n\n## API\n\n```js\nvar accepts = require('accepts')\n```\n\n### accepts(req)\n\nCreate a new `Accepts` object for the given `req`.\n\n#### .charset(charsets)\n\nReturn the first accepted charset. If nothing in `charsets` is accepted,\nthen `false` is returned.\n\n#### .charsets()\n\nReturn the charsets that the request accepts, in the order of the client's\npreference (most preferred first).\n\n#### .encoding(encodings)\n\nReturn the first accepted encoding. If nothing in `encodings` is accepted,\nthen `false` is returned.\n\n#### .encodings()\n\nReturn the encodings that the request accepts, in the order of the client's\npreference (most preferred first).\n\n#### .language(languages)\n\nReturn the first accepted language. If nothing in `languages` is accepted,\nthen `false` is returned.\n\n#### .languages()\n\nReturn the languages that the request accepts, in the order of the client's\npreference (most preferred first).\n\n#### .type(types)\n\nReturn the first accepted type (and it is returned as the same text as what\nappears in the `types` array). If nothing in `types` is accepted, then `false`\nis returned.\n\nThe `types` array can contain full MIME types or file extensions. Any value\nthat is not a full MIME types is passed to `require('mime-types').lookup`.\n\n#### .types()\n\nReturn the types that the request accepts, in the order of the client's\npreference (most preferred first).\n\n## Examples\n\n### Simple type negotiation\n\nThis simple example shows how to use `accepts` to return a different typed\nrespond body based on what the client wants to accept. The server lists it's\npreferences in order and will get back the best match between the client and\nserver.\n\n```js\nvar accepts = require('accepts')\nvar http = require('http')\n\nfunction app(req, res) {\n var accept = accepts(req)\n\n // the order of this list is significant; should be server preferred order\n switch(accept.type(['json', 'html'])) {\n case 'json':\n res.setHeader('Content-Type', 'application/json')\n res.write('{\"hello\":\"world!\"}')\n break\n case 'html':\n res.setHeader('Content-Type', 'text/html')\n res.write('hello, world!')\n break\n default:\n // the fallback is text/plain, so no need to specify it above\n res.setHeader('Content-Type', 'text/plain')\n res.write('hello, world!')\n break\n }\n\n res.end()\n}\n\nhttp.createServer(app).listen(3000)\n```\n\nYou can test this out with the cURL program:\n```sh\ncurl -I -H'Accept: text/html' http://localhost:3000/\n```\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/accepts.svg\n[npm-url]: https://npmjs.org/package/accepts\n[node-version-image]: https://img.shields.io/node/v/accepts.svg\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/accepts/master.svg\n[travis-url]: https://travis-ci.org/jshttp/accepts\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/accepts/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/accepts\n[downloads-image]: https://img.shields.io/npm/dm/accepts.svg\n[downloads-url]: https://npmjs.org/package/accepts\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/accepts/issues" }, - "homepage": "https://github.com/jshttp/accepts", - "_id": "accepts@1.1.4", - "_shasum": "d71c96f7d41d0feda2c38cd14e8a27c04158df4a", - "_from": "accepts@~1.1.3", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "federomero", - "email": "federomero@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "shtylman", - "email": "shtylman@gmail.com" - }, - { - "name": "mscdex", - "email": "mscdex@mscdex.net" - }, - { - "name": "fishrock123", - "email": "fishrock123@rocketmail.com" - } - ], + "_id": "accepts@1.2.9", "dist": { - "shasum": "d71c96f7d41d0feda2c38cd14e8a27c04158df4a", - "tarball": "http://registry.npmjs.org/accepts/-/accepts-1.1.4.tgz" + "shasum": "78c123eccee774e07d283f201b3227b2a6676658" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.1.4.tgz" + "_from": "accepts@~1.2.7", + "_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.2.9.tgz" } diff --git a/server/node_modules/express/node_modules/content-disposition/HISTORY.md b/server/node_modules/express/node_modules/content-disposition/HISTORY.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/content-disposition/LICENSE b/server/node_modules/express/node_modules/content-disposition/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/content-disposition/README.md b/server/node_modules/express/node_modules/content-disposition/README.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/content-disposition/index.js b/server/node_modules/express/node_modules/content-disposition/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/content-disposition/package.json b/server/node_modules/express/node_modules/content-disposition/package.json old mode 100755 new mode 100644 index b0bb7ec6..175662fd --- a/server/node_modules/express/node_modules/content-disposition/package.json +++ b/server/node_modules/express/node_modules/content-disposition/package.json @@ -17,7 +17,7 @@ ], "repository": { "type": "git", - "url": "https://github.com/jshttp/content-disposition" + "url": "git://github.com/jshttp/content-disposition" }, "devDependencies": { "istanbul": "0.3.2", @@ -37,30 +37,11 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" }, - "gitHead": "f3c915f0c9d9f5ec79713dba24c8c6181b73305d", + "readme": "# content-disposition\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nCreate and parse HTTP `Content-Disposition` header\n\n## Installation\n\n```sh\n$ npm install content-disposition\n```\n\n## API\n\n```js\nvar contentDisposition = require('content-disposition')\n```\n\n### contentDisposition(filename, options)\n\nCreate an attachment `Content-Disposition` header value using the given file name,\nif supplied. The `filename` is optional and if no file name is desired, but you\nwant to specify `options`, set `filename` to `undefined`.\n\n```js\nres.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf'))\n```\n\n**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this\nheader through a means different from `setHeader` in Node.js, you'll want to specify\nthe `'binary'` encoding in Node.js.\n\n#### Options\n\n`contentDisposition` accepts these properties in the options object.\n\n##### fallback\n\nIf the `filename` option is outside ISO-8859-1, then the file name is actually\nstored in a supplemental field for clients that support Unicode file names and\na ISO-8859-1 version of the file name is automatically generated.\n\nThis specifies the ISO-8859-1 file name to override the automatic generation or\ndisables the generation all together, defaults to `true`.\n\n - A string will specify the ISO-8859-1 file name to use in place of automatic\n generation.\n - `false` will disable including a ISO-8859-1 file name and only include the\n Unicode version (unless the file name is already ISO-8859-1).\n - `true` will enable automatic generation if the file name is outside ISO-8859-1.\n\nIf the `filename` option is ISO-8859-1 and this option is specified and has a\ndifferent value, then the `filename` option is encoded in the extended field\nand this set as the fallback field, even though they are both ISO-8859-1.\n\n##### type\n\nSpecifies the disposition type, defaults to `\"attachment\"`. This can also be\n`\"inline\"`, or any other value (all values except inline are treated like\n`attachment`, but can convey additional information if both parties agree to\nit). The type is normalized to lower-case.\n\n### contentDisposition.parse(string)\n\n```js\nvar disposition = contentDisposition.parse('attachment; filename=\"EURO rates.txt\"; filename*=UTF-8\\'\\'%e2%82%ac%20rates.txt\"');\n```\n\nParse a `Content-Disposition` header string. This automatically handles extended\n(\"Unicode\") parameters by decoding them and providing them under the standard\nparameter name. This will return an object with the following properties (examples\nare shown for the string `'attachment; filename=\"EURO rates.txt\"; filename*=UTF-8\\'\\'%e2%82%ac%20rates.txt'`):\n\n - `type`: The disposition type (always lower case). Example: `'attachment'`\n\n - `parameters`: An object of the parameters in the disposition (name of parameter\n always lower case and extended versions replace non-extended versions). Example:\n `{filename: \"€ rates.txt\"}`\n\n## Examples\n\n### Send a file for download\n\n```js\nvar contentDisposition = require('content-disposition')\nvar destroy = require('destroy')\nvar http = require('http')\nvar onFinished = require('on-finished')\n\nvar filePath = '/path/to/public/plans.pdf'\n\nhttp.createServer(function onRequest(req, res) {\n // set headers\n res.setHeader('Content-Type', 'application/pdf')\n res.setHeader('Content-Disposition', contentDisposition(filePath))\n\n // send file\n var stream = fs.createReadStream(filePath)\n stream.pipe(res)\n onFinished(res, function (err) {\n destroy(stream)\n })\n})\n```\n\n## Testing\n\n```sh\n$ npm test\n```\n\n## References\n\n- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616]\n- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987]\n- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266]\n- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231]\n\n[rfc-2616]: https://tools.ietf.org/html/rfc2616\n[rfc-5987]: https://tools.ietf.org/html/rfc5987\n[rfc-6266]: https://tools.ietf.org/html/rfc6266\n[tc-2231]: http://greenbytes.de/tech/tc2231/\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/content-disposition.svg?style=flat\n[npm-url]: https://npmjs.org/package/content-disposition\n[node-version-image]: https://img.shields.io/node/v/content-disposition.svg?style=flat\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg?style=flat\n[travis-url]: https://travis-ci.org/jshttp/content-disposition\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg?style=flat\n[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg?style=flat\n[downloads-url]: https://npmjs.org/package/content-disposition\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/content-disposition/issues" }, - "homepage": "https://github.com/jshttp/content-disposition", "_id": "content-disposition@0.5.0", - "_shasum": "4284fe6ae0630874639e44e80a418c2934135e9e", - "_from": "content-disposition@0.5.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], - "dist": { - "shasum": "4284fe6ae0630874639e44e80a418c2934135e9e", - "tarball": "http://registry.npmjs.org/content-disposition/-/content-disposition-0.5.0.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.0.tgz", - "readme": "ERROR: No README data found!" + "_from": "content-disposition@0.5.0" } diff --git a/server/node_modules/express/node_modules/cookie-signature/.npmignore b/server/node_modules/express/node_modules/cookie-signature/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/cookie-signature/History.md b/server/node_modules/express/node_modules/cookie-signature/History.md old mode 100755 new mode 100644 index 2bbc4b39..78513cc3 --- a/server/node_modules/express/node_modules/cookie-signature/History.md +++ b/server/node_modules/express/node_modules/cookie-signature/History.md @@ -1,9 +1,20 @@ +1.0.6 / 2015-02-03 +================== + +* use `npm test` instead of `make test` to run tests +* clearer assertion messages when checking input + + +1.0.5 / 2014-09-05 +================== + +* add license to package.json + 1.0.4 / 2014-06-25 ================== * corrected avoidance of timing attacks (thanks @tenbits!) - 1.0.3 / 2014-01-28 ================== diff --git a/server/node_modules/express/node_modules/cookie-signature/Makefile b/server/node_modules/express/node_modules/cookie-signature/Makefile deleted file mode 100755 index 4e9c8d36..00000000 --- a/server/node_modules/express/node_modules/cookie-signature/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --require should \ - --reporter spec - -.PHONY: test \ No newline at end of file diff --git a/server/node_modules/express/node_modules/cookie-signature/Readme.md b/server/node_modules/express/node_modules/cookie-signature/Readme.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/cookie-signature/index.js b/server/node_modules/express/node_modules/cookie-signature/index.js old mode 100755 new mode 100644 index b63bf84a..b8c9463a --- a/server/node_modules/express/node_modules/cookie-signature/index.js +++ b/server/node_modules/express/node_modules/cookie-signature/index.js @@ -14,8 +14,8 @@ var crypto = require('crypto'); */ exports.sign = function(val, secret){ - if ('string' != typeof val) throw new TypeError('cookie required'); - if ('string' != typeof secret) throw new TypeError('secret required'); + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); return val + '.' + crypto .createHmac('sha256', secret) .update(val) @@ -34,8 +34,8 @@ exports.sign = function(val, secret){ */ exports.unsign = function(val, secret){ - if ('string' != typeof val) throw new TypeError('cookie required'); - if ('string' != typeof secret) throw new TypeError('secret required'); + if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); var str = val.slice(0, val.lastIndexOf('.')) , mac = exports.sign(str, secret); diff --git a/server/node_modules/express/node_modules/cookie-signature/package.json b/server/node_modules/express/node_modules/cookie-signature/package.json old mode 100755 new mode 100644 index 741961f8..91ae40e1 --- a/server/node_modules/express/node_modules/cookie-signature/package.json +++ b/server/node_modules/express/node_modules/cookie-signature/package.json @@ -1,6 +1,6 @@ { "name": "cookie-signature", - "version": "1.0.5", + "version": "1.0.6", "description": "Sign and unsign cookies", "keywords": [ "cookie", @@ -21,36 +21,15 @@ "mocha": "*", "should": "*" }, + "scripts": { + "test": "mocha --require should --reporter spec" + }, "main": "index", - "gitHead": "73ed69b511b3ef47555d71b4ed1deea9e5ed6e1f", + "readme": "\n# cookie-signature\n\n Sign and unsign cookies.\n\n## Example\n\n```js\nvar cookie = require('cookie-signature');\n\nvar val = cookie.sign('hello', 'tobiiscool');\nval.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI');\n\nvar val = cookie.sign('hello', 'tobiiscool');\ncookie.unsign(val, 'tobiiscool').should.equal('hello');\ncookie.unsign(val, 'luna').should.be.false;\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 LearnBoost <tj@learnboost.com>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", + "readmeFilename": "Readme.md", "bugs": { "url": "https://github.com/visionmedia/node-cookie-signature/issues" }, - "homepage": "https://github.com/visionmedia/node-cookie-signature", - "_id": "cookie-signature@1.0.5", - "scripts": {}, - "_shasum": "a122e3f1503eca0f5355795b0711bb2368d450f9", - "_from": "cookie-signature@1.0.5", - "_npmVersion": "1.4.20", - "_npmUser": { - "name": "natevw", - "email": "natevw@yahoo.com" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "natevw", - "email": "natevw@yahoo.com" - } - ], - "dist": { - "shasum": "a122e3f1503eca0f5355795b0711bb2368d450f9", - "tarball": "http://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.5.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.5.tgz", - "readme": "ERROR: No README data found!" + "_id": "cookie-signature@1.0.6", + "_from": "cookie-signature@1.0.6" } diff --git a/server/node_modules/express/node_modules/cookie/.npmignore b/server/node_modules/express/node_modules/cookie/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/cookie/LICENSE b/server/node_modules/express/node_modules/cookie/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/cookie/README.md b/server/node_modules/express/node_modules/cookie/README.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/cookie/index.js b/server/node_modules/express/node_modules/cookie/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/cookie/package.json b/server/node_modules/express/node_modules/cookie/package.json old mode 100755 new mode 100644 index 7dbb395f..067e2023 --- a/server/node_modules/express/node_modules/cookie/package.json +++ b/server/node_modules/express/node_modules/cookie/package.json @@ -26,29 +26,15 @@ "engines": { "node": "*" }, + "readme": "# cookie [![Build Status](https://secure.travis-ci.org/defunctzombie/node-cookie.png?branch=master)](http://travis-ci.org/defunctzombie/node-cookie) #\n\ncookie is a basic cookie parser and serializer. It doesn't make assumptions about how you are going to deal with your cookies. It basically just provides a way to read and write the HTTP cookie headers.\n\nSee [RFC6265](http://tools.ietf.org/html/rfc6265) for details about the http header for cookies.\n\n## how?\n\n```\nnpm install cookie\n```\n\n```javascript\nvar cookie = require('cookie');\n\nvar hdr = cookie.serialize('foo', 'bar');\n// hdr = 'foo=bar';\n\nvar cookies = cookie.parse('foo=bar; cat=meow; dog=ruff');\n// cookies = { foo: 'bar', cat: 'meow', dog: 'ruff' };\n```\n\n## more\n\nThe serialize function takes a third parameter, an object, to set cookie options. See the RFC for valid values.\n\n### path\n> cookie path\n\n### expires\n> absolute expiration date for the cookie (Date object)\n\n### maxAge\n> relative max age of the cookie from when the client receives it (seconds)\n\n### domain\n> domain for the cookie\n\n### secure\n> true or false\n\n### httpOnly\n> true or false\n\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/shtylman/node-cookie/issues" }, - "homepage": "https://github.com/shtylman/node-cookie", "_id": "cookie@0.1.2", "dist": { - "shasum": "72fec3d24e48a3432073d90c12642005061004b1", - "tarball": "http://registry.npmjs.org/cookie/-/cookie-0.1.2.tgz" + "shasum": "1eef0dec7e54f653c66b69d1428efc5e3c52c0ef" }, "_from": "cookie@0.1.2", - "_npmVersion": "1.4.6", - "_npmUser": { - "name": "shtylman", - "email": "shtylman@gmail.com" - }, - "maintainers": [ - { - "name": "shtylman", - "email": "shtylman@gmail.com" - } - ], - "directories": {}, - "_shasum": "72fec3d24e48a3432073d90c12642005061004b1", - "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.1.2.tgz", - "readme": "ERROR: No README data found!" + "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.1.2.tgz" } diff --git a/server/node_modules/express/node_modules/debug/.jshintrc b/server/node_modules/express/node_modules/debug/.jshintrc old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/debug/.npmignore b/server/node_modules/express/node_modules/debug/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/debug/History.md b/server/node_modules/express/node_modules/debug/History.md old mode 100755 new mode 100644 index 770e4832..854c9711 --- a/server/node_modules/express/node_modules/debug/History.md +++ b/server/node_modules/express/node_modules/debug/History.md @@ -1,4 +1,13 @@ +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + 2.1.3 / 2015-03-13 ================== diff --git a/server/node_modules/express/node_modules/debug/Makefile b/server/node_modules/express/node_modules/debug/Makefile old mode 100755 new mode 100644 index b0bde6e6..5cf4a596 --- a/server/node_modules/express/node_modules/debug/Makefile +++ b/server/node_modules/express/node_modules/debug/Makefile @@ -16,7 +16,7 @@ all: dist/debug.js install: node_modules clean: - @rm -rf node_modules dist + @rm -rf dist dist: @mkdir -p $@ @@ -26,8 +26,11 @@ dist/debug.js: node_modules browser.js debug.js dist --standalone debug \ . > $@ +distclean: clean + @rm -rf node_modules + node_modules: package.json @NODE_ENV= $(NPM) install @touch node_modules -.PHONY: all install clean +.PHONY: all install clean distclean diff --git a/server/node_modules/express/node_modules/debug/Readme.md b/server/node_modules/express/node_modules/debug/Readme.md old mode 100755 new mode 100644 index 14222e0c..b4f45e3c --- a/server/node_modules/express/node_modules/debug/Readme.md +++ b/server/node_modules/express/node_modules/debug/Readme.md @@ -53,8 +53,8 @@ setInterval(function(){ #### Windows note - On Windows the environment variable is set using the `set` command. - + On Windows the environment variable is set using the `set` command. + ```cmd set DEBUG=*,-not_this ``` @@ -77,7 +77,7 @@ Then, run the program to be debugged as usual. ## Wildcards - The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". @@ -147,6 +147,16 @@ error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` +### Save debug output to a file + +You can save all debug statements to a file by piping them. + +Example: + +```bash +$ DEBUG_FD=3 node your-app.js 3> whatever.log +``` + ## Authors - TJ Holowaychuk diff --git a/server/node_modules/express/node_modules/debug/bower.json b/server/node_modules/express/node_modules/debug/bower.json old mode 100755 new mode 100644 index f7d3f6dc..6af573ff --- a/server/node_modules/express/node_modules/debug/bower.json +++ b/server/node_modules/express/node_modules/debug/bower.json @@ -1,7 +1,7 @@ { "name": "visionmedia-debug", "main": "dist/debug.js", - "version": "2.1.3", + "version": "2.2.0", "homepage": "https://github.com/visionmedia/debug", "authors": [ "TJ Holowaychuk " diff --git a/server/node_modules/express/node_modules/debug/browser.js b/server/node_modules/express/node_modules/debug/browser.js old mode 100755 new mode 100644 index 55f4cf92..7c764522 --- a/server/node_modules/express/node_modules/debug/browser.js +++ b/server/node_modules/express/node_modules/debug/browser.js @@ -11,17 +11,10 @@ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; - -/** - * Use chrome.storage.local if we are in an app - */ - -var storage; - -if (typeof chrome !== 'undefined' && typeof chrome.storage !== 'undefined') - storage = chrome.storage.local; -else - storage = localstorage(); +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); /** * Colors. @@ -129,9 +122,9 @@ function log() { function save(namespaces) { try { if (null == namespaces) { - storage.removeItem('debug'); + exports.storage.removeItem('debug'); } else { - storage.debug = namespaces; + exports.storage.debug = namespaces; } } catch(e) {} } @@ -146,7 +139,7 @@ function save(namespaces) { function load() { var r; try { - r = storage.debug; + r = exports.storage.debug; } catch(e) {} return r; } diff --git a/server/node_modules/express/node_modules/debug/component.json b/server/node_modules/express/node_modules/debug/component.json old mode 100755 new mode 100644 index 52ffd422..ca106372 --- a/server/node_modules/express/node_modules/debug/component.json +++ b/server/node_modules/express/node_modules/debug/component.json @@ -2,7 +2,7 @@ "name": "debug", "repo": "visionmedia/debug", "description": "small debugging utility", - "version": "2.1.3", + "version": "2.2.0", "keywords": [ "debug", "log", @@ -14,6 +14,6 @@ "debug.js" ], "dependencies": { - "rauchg/ms.js": "0.7.0" + "rauchg/ms.js": "0.7.1" } } diff --git a/server/node_modules/express/node_modules/debug/debug.js b/server/node_modules/express/node_modules/debug/debug.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/debug/node.js b/server/node_modules/express/node_modules/debug/node.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/debug/node_modules/ms/.npmignore b/server/node_modules/express/node_modules/debug/node_modules/ms/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/debug/node_modules/ms/LICENSE b/server/node_modules/express/node_modules/debug/node_modules/ms/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/debug/node_modules/ms/README.md b/server/node_modules/express/node_modules/debug/node_modules/ms/README.md old mode 100755 new mode 100644 index 0fd54fdc..9b4fd035 --- a/server/node_modules/express/node_modules/debug/node_modules/ms/README.md +++ b/server/node_modules/express/node_modules/debug/node_modules/ms/README.md @@ -23,7 +23,7 @@ ms(2 * 60000, { long: true }) // "2 minutes" ms(ms('10 hours'), { long: true }) // "10 hours" ``` -- Node/Browser compatible. Published as [`ms`](https://www.npmjs.org/package/ms) in [NPM](nodejs.org/download). +- Node/Browser compatible. Published as [`ms`](https://www.npmjs.org/package/ms) in [NPM](http://nodejs.org/download). - If a number is supplied to `ms`, a string with a unit is returned. - If a string that contains the number is supplied, it returns it as a number (e.g: it returns `100` for `'100'`). diff --git a/server/node_modules/express/node_modules/debug/node_modules/ms/index.js b/server/node_modules/express/node_modules/debug/node_modules/ms/index.js old mode 100755 new mode 100644 index e79bfa18..4f927716 --- a/server/node_modules/express/node_modules/debug/node_modules/ms/index.js +++ b/server/node_modules/express/node_modules/debug/node_modules/ms/index.js @@ -38,6 +38,8 @@ module.exports = function(val, options){ */ function parse(str) { + str = '' + str; + if (str.length > 10000) return; var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); if (!match) return; var n = parseFloat(match[1]); diff --git a/server/node_modules/express/node_modules/debug/node_modules/ms/package.json b/server/node_modules/express/node_modules/debug/node_modules/ms/package.json old mode 100755 new mode 100644 index f1e5ef8f..a273574f --- a/server/node_modules/express/node_modules/debug/node_modules/ms/package.json +++ b/server/node_modules/express/node_modules/debug/node_modules/ms/package.json @@ -1,6 +1,6 @@ { "name": "ms", - "version": "0.7.0", + "version": "0.7.1", "description": "Tiny ms conversion utility", "repository": { "type": "git", @@ -17,30 +17,15 @@ "ms/index.js": "index.js" } }, - "gitHead": "1e9cd9b05ef0dc26f765434d2bfee42394376e52", + "readme": "# ms.js: miliseconds conversion utility\n\n```js\nms('2 days') // 172800000\nms('1d') // 86400000\nms('10h') // 36000000\nms('2.5 hrs') // 9000000\nms('2h') // 7200000\nms('1m') // 60000\nms('5s') // 5000\nms('100') // 100\n```\n\n```js\nms(60000) // \"1m\"\nms(2 * 60000) // \"2m\"\nms(ms('10 hours')) // \"10h\"\n```\n\n```js\nms(60000, { long: true }) // \"1 minute\"\nms(2 * 60000, { long: true }) // \"2 minutes\"\nms(ms('10 hours'), { long: true }) // \"10 hours\"\n```\n\n- Node/Browser compatible. Published as [`ms`](https://www.npmjs.org/package/ms) in [NPM](http://nodejs.org/download).\n- If a number is supplied to `ms`, a string with a unit is returned.\n- If a string that contains the number is supplied, it returns it as\na number (e.g: it returns `100` for `'100'`).\n- If you pass a string with a number and a valid unit, the number of\nequivalent ms is returned.\n\n## License\n\nMIT\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/guille/ms.js/issues" }, - "homepage": "https://github.com/guille/ms.js", - "_id": "ms@0.7.0", - "scripts": {}, - "_shasum": "865be94c2e7397ad8a57da6a633a6e2f30798b83", - "_from": "ms@0.7.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "rauchg", - "email": "rauchg@gmail.com" - }, - "maintainers": [ - { - "name": "rauchg", - "email": "rauchg@gmail.com" - } - ], + "_id": "ms@0.7.1", "dist": { - "shasum": "865be94c2e7397ad8a57da6a633a6e2f30798b83", - "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.0.tgz" + "shasum": "71c4b4174f5b6aa0101eb56e733ee5f6b4c1a917" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.0.tgz" + "_from": "ms@0.7.1", + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz" } diff --git a/server/node_modules/express/node_modules/debug/package.json b/server/node_modules/express/node_modules/debug/package.json old mode 100755 new mode 100644 index c703a948..7b8855f3 --- a/server/node_modules/express/node_modules/debug/package.json +++ b/server/node_modules/express/node_modules/debug/package.json @@ -1,6 +1,6 @@ { "name": "debug", - "version": "2.1.3", + "version": "2.2.0", "repository": { "type": "git", "url": "git://github.com/visionmedia/debug.git" @@ -24,7 +24,7 @@ ], "license": "MIT", "dependencies": { - "ms": "0.7.0" + "ms": "0.7.1" }, "devDependencies": { "browserify": "9.0.3", @@ -38,35 +38,11 @@ "debug/debug.js": "debug.js" } }, - "gitHead": "0a8e4b7e0d2d1b55ef4e7422498ca24c677ae63a", + "readme": "# debug\n\n tiny node.js debugging utility modelled after node core's debugging technique.\n\n## Installation\n\n```bash\n$ npm install debug\n```\n\n## Usage\n\n With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.\n\nExample _app.js_:\n\n```js\nvar debug = require('debug')('http')\n , http = require('http')\n , name = 'My App';\n\n// fake app\n\ndebug('booting %s', name);\n\nhttp.createServer(function(req, res){\n debug(req.method + ' ' + req.url);\n res.end('hello\\n');\n}).listen(3000, function(){\n debug('listening');\n});\n\n// fake worker of some kind\n\nrequire('./worker');\n```\n\nExample _worker.js_:\n\n```js\nvar debug = require('debug')('worker');\n\nsetInterval(function(){\n debug('doing some work');\n}, 1000);\n```\n\n The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:\n\n ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)\n\n ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)\n\n#### Windows note\n\n On Windows the environment variable is set using the `set` command.\n\n ```cmd\n set DEBUG=*,-not_this\n ```\n\nThen, run the program to be debugged as usual.\n\n## Millisecond diff\n\n When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the \"+NNNms\" will show you how much time was spent between calls.\n\n ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)\n\n When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:\n\n ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)\n\n## Conventions\n\n If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use \":\" to separate features. For example \"bodyParser\" from Connect would then be \"connect:bodyParser\".\n\n## Wildcards\n\n The `*` character may be used as a wildcard. Suppose for example your library has debuggers named \"connect:bodyParser\", \"connect:compress\", \"connect:session\", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.\n\n You can also exclude specific debuggers by prefixing them with a \"-\" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with \"connect:\".\n\n## Browser support\n\n Debug works in the browser as well, currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. Somewhere in the code on your page, include:\n\n```js\nwindow.myDebug = require(\"debug\");\n```\n\n (\"debug\" is a global object in the browser so we give this object a different name.) When your page is open in the browser, type the following in the console:\n\n```js\nmyDebug.enable(\"worker:*\")\n```\n\n Refresh the page. Debug output will continue to be sent to the console until it is disabled by typing `myDebug.disable()` in the console.\n\n```js\na = debug('worker:a');\nb = debug('worker:b');\n\nsetInterval(function(){\n a('doing some work');\n}, 1000);\n\nsetInterval(function(){\n b('doing some work');\n}, 1200);\n```\n\n#### Web Inspector Colors\n\n Colors are also enabled on \"Web Inspectors\" that understand the `%c` formatting\n option. These are WebKit web inspectors, Firefox ([since version\n 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))\n and the Firebug plugin for Firefox (any version).\n\n Colored output looks something like:\n\n ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png)\n\n### stderr vs stdout\n\nYou can set an alternative logging method per-namespace by overriding the `log` method on a per-namespace or globally:\n\nExample _stdout.js_:\n\n```js\nvar debug = require('debug');\nvar error = debug('app:error');\n\n// by default stderr is used\nerror('goes to stderr!');\n\nvar log = debug('app:log');\n// set this namespace to log via console.log\nlog.log = console.log.bind(console); // don't forget to bind to console!\nlog('goes to stdout');\nerror('still goes to stderr!');\n\n// set all output to go via console.info\n// overrides all per-namespace log settings\ndebug.log = console.info.bind(console);\nerror('now goes to stdout via console.info');\nlog('still goes to stdout, but via console.info now');\n```\n\n### Save debug output to a file\n\nYou can save all debug statements to a file by piping them.\n\nExample:\n\n```bash\n$ DEBUG_FD=3 node your-app.js 3> whatever.log\n```\n\n## Authors\n\n - TJ Holowaychuk\n - Nathan Rajlich\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "Readme.md", "bugs": { "url": "https://github.com/visionmedia/debug/issues" }, - "homepage": "https://github.com/visionmedia/debug", - "_id": "debug@2.1.3", - "scripts": {}, - "_shasum": "ce8ab1b5ee8fbee2bfa3b633cab93d366b63418e", - "_from": "debug@~2.1.0", - "_npmVersion": "2.5.1", - "_nodeVersion": "0.12.0", - "_npmUser": { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - } - ], - "dist": { - "shasum": "ce8ab1b5ee8fbee2bfa3b633cab93d366b63418e", - "tarball": "http://registry.npmjs.org/debug/-/debug-2.1.3.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/debug/-/debug-2.1.3.tgz" + "_id": "debug@2.2.0", + "_from": "debug@~2.2.0" } diff --git a/server/node_modules/express/node_modules/depd/History.md b/server/node_modules/express/node_modules/depd/History.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/depd/LICENSE b/server/node_modules/express/node_modules/depd/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/depd/Readme.md b/server/node_modules/express/node_modules/depd/Readme.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/depd/index.js b/server/node_modules/express/node_modules/depd/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js b/server/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js b/server/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/depd/lib/compat/index.js b/server/node_modules/express/node_modules/depd/lib/compat/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/depd/package.json b/server/node_modules/express/node_modules/depd/package.json old mode 100755 new mode 100644 index 6adbbe07..7b66fb7c --- a/server/node_modules/express/node_modules/depd/package.json +++ b/server/node_modules/express/node_modules/depd/package.json @@ -13,7 +13,7 @@ ], "repository": { "type": "git", - "url": "https://github.com/dougwilson/nodejs-depd" + "url": "git://github.com/dougwilson/nodejs-depd" }, "devDependencies": { "benchmark": "1.0.0", @@ -37,29 +37,11 @@ "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --no-exit test/", "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/" }, - "gitHead": "769e0f8108463c35a6937a9d634ab19fee45100a", + "readme": "# depd\n\n[![NPM Version][npm-version-image]][npm-url]\n[![NPM Downloads][npm-downloads-image]][npm-url]\n[![Node.js Version][node-image]][node-url]\n[![Linux Build][travis-image]][travis-url]\n[![Windows Build][appveyor-image]][appveyor-url]\n[![Coverage Status][coveralls-image]][coveralls-url]\n[![Gratipay][gratipay-image]][gratipay-url]\n\nDeprecate all the things\n\n> With great modules comes great responsibility; mark things deprecated!\n\n## Install\n\n```sh\n$ npm install depd\n```\n\n## API\n\n```js\nvar deprecate = require('depd')('my-module')\n```\n\nThis library allows you to display deprecation messages to your users.\nThis library goes above and beyond with deprecation warnings by\nintrospection of the call stack (but only the bits that it is interested\nin).\n\nInstead of just warning on the first invocation of a deprecated\nfunction and never again, this module will warn on the first invocation\nof a deprecated function per unique call site, making it ideal to alert\nusers of all deprecated uses across the code base, rather than just\nwhatever happens to execute first.\n\nThe deprecation warnings from this module also include the file and line\ninformation for the call into the module that the deprecated function was\nin.\n\n**NOTE** this library has a similar interface to the `debug` module, and\nthis module uses the calling file to get the boundary for the call stacks,\nso you should always create a new `deprecate` object in each file and not\nwithin some central file.\n\n### depd(namespace)\n\nCreate a new deprecate function that uses the given namespace name in the\nmessages and will display the call site prior to the stack entering the\nfile this function was called from. It is highly suggested you use the\nname of your module as the namespace.\n\n### deprecate(message)\n\nCall this function from deprecated code to display a deprecation message.\nThis message will appear once per unique caller site. Caller site is the\nfirst call site in the stack in a different file from the caller of this\nfunction.\n\nIf the message is omitted, a message is generated for you based on the site\nof the `deprecate()` call and will display the name of the function called,\nsimilar to the name displayed in a stack trace.\n\n### deprecate.function(fn, message)\n\nCall this function to wrap a given function in a deprecation message on any\ncall to the function. An optional message can be supplied to provide a custom\nmessage.\n\n### deprecate.property(obj, prop, message)\n\nCall this function to wrap a given property on object in a deprecation message\non any accessing or setting of the property. An optional message can be supplied\nto provide a custom message.\n\nThe method must be called on the object where the property belongs (not\ninherited from the prototype).\n\nIf the property is a data descriptor, it will be converted to an accessor\ndescriptor in order to display the deprecation message.\n\n### process.on('deprecation', fn)\n\nThis module will allow easy capturing of deprecation errors by emitting the\nerrors as the type \"deprecation\" on the global `process`. If there are no\nlisteners for this type, the errors are written to STDERR as normal, but if\nthere are any listeners, nothing will be written to STDERR and instead only\nemitted. From there, you can write the errors in a different format or to a\nlogging source.\n\nThe error represents the deprecation and is emitted only once with the same\nrules as writing to STDERR. The error has the following properties:\n\n - `message` - This is the message given by the library\n - `name` - This is always `'DeprecationError'`\n - `namespace` - This is the namespace the deprecation came from\n - `stack` - This is the stack of the call to the deprecated thing\n\nExample `error.stack` output:\n\n```\nDeprecationError: my-cool-module deprecated oldfunction\n at Object. ([eval]-wrapper:6:22)\n at Module._compile (module.js:456:26)\n at evalScript (node.js:532:25)\n at startup (node.js:80:7)\n at node.js:902:3\n```\n\n### process.env.NO_DEPRECATION\n\nAs a user of modules that are deprecated, the environment variable `NO_DEPRECATION`\nis provided as a quick solution to silencing deprecation warnings from being\noutput. The format of this is similar to that of `DEBUG`:\n\n```sh\n$ NO_DEPRECATION=my-module,othermod node app.js\n```\n\nThis will suppress deprecations from being output for \"my-module\" and \"othermod\".\nThe value is a list of comma-separated namespaces. To suppress every warning\nacross all namespaces, use the value `*` for a namespace.\n\nProviding the argument `--no-deprecation` to the `node` executable will suppress\nall deprecations (only available in Node.js 0.8 or higher).\n\n**NOTE** This will not suppress the deperecations given to any \"deprecation\"\nevent listeners, just the output to STDERR.\n\n### process.env.TRACE_DEPRECATION\n\nAs a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION`\nis provided as a solution to getting more detailed location information in deprecation\nwarnings by including the entire stack trace. The format of this is the same as\n`NO_DEPRECATION`:\n\n```sh\n$ TRACE_DEPRECATION=my-module,othermod node app.js\n```\n\nThis will include stack traces for deprecations being output for \"my-module\" and\n\"othermod\". The value is a list of comma-separated namespaces. To trace every\nwarning across all namespaces, use the value `*` for a namespace.\n\nProviding the argument `--trace-deprecation` to the `node` executable will trace\nall deprecations (only available in Node.js 0.8 or higher).\n\n**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`.\n\n## Display\n\n![message](files/message.png)\n\nWhen a user calls a function in your library that you mark deprecated, they\nwill see the following written to STDERR (in the given colors, similar colors\nand layout to the `debug` module):\n\n```\nbright cyan bright yellow\n| | reset cyan\n| | | |\n▼ ▼ ▼ ▼\nmy-cool-module deprecated oldfunction [eval]-wrapper:6:22\n▲ ▲ ▲ ▲\n| | | |\nnamespace | | location of mycoolmod.oldfunction() call\n | deprecation message\n the word \"deprecated\"\n```\n\nIf the user redirects their STDERR to a file or somewhere that does not support\ncolors, they see (similar layout to the `debug` module):\n\n```\nSun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22\n▲ ▲ ▲ ▲ ▲\n| | | | |\ntimestamp of message namespace | | location of mycoolmod.oldfunction() call\n | deprecation message\n the word \"deprecated\"\n```\n\n## Examples\n\n### Deprecating all calls to a function\n\nThis will display a deprecated message about \"oldfunction\" being deprecated\nfrom \"my-module\" on STDERR.\n\n```js\nvar deprecate = require('depd')('my-cool-module')\n\n// message automatically derived from function name\n// Object.oldfunction\nexports.oldfunction = deprecate.function(function oldfunction() {\n // all calls to function are deprecated\n})\n\n// specific message\nexports.oldfunction = deprecate.function(function () {\n // all calls to function are deprecated\n}, 'oldfunction')\n```\n\n### Conditionally deprecating a function call\n\nThis will display a deprecated message about \"weirdfunction\" being deprecated\nfrom \"my-module\" on STDERR when called with less than 2 arguments.\n\n```js\nvar deprecate = require('depd')('my-cool-module')\n\nexports.weirdfunction = function () {\n if (arguments.length < 2) {\n // calls with 0 or 1 args are deprecated\n deprecate('weirdfunction args < 2')\n }\n}\n```\n\nWhen calling `deprecate` as a function, the warning is counted per call site\nwithin your own module, so you can display different deprecations depending\non different situations and the users will still get all the warnings:\n\n```js\nvar deprecate = require('depd')('my-cool-module')\n\nexports.weirdfunction = function () {\n if (arguments.length < 2) {\n // calls with 0 or 1 args are deprecated\n deprecate('weirdfunction args < 2')\n } else if (typeof arguments[0] !== 'string') {\n // calls with non-string first argument are deprecated\n deprecate('weirdfunction non-string first arg')\n }\n}\n```\n\n### Deprecating property access\n\nThis will display a deprecated message about \"oldprop\" being deprecated\nfrom \"my-module\" on STDERR when accessed. A deprecation will be displayed\nwhen setting the value and when getting the value.\n\n```js\nvar deprecate = require('depd')('my-cool-module')\n\nexports.oldprop = 'something'\n\n// message automatically derives from property name\ndeprecate.property(exports, 'oldprop')\n\n// explicit message\ndeprecate.property(exports, 'oldprop', 'oldprop >= 0.10')\n```\n\n## License\n\n[MIT](LICENSE)\n\n[npm-version-image]: https://img.shields.io/npm/v/depd.svg\n[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg\n[npm-url]: https://npmjs.org/package/depd\n[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux\n[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd\n[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows\n[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd\n[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg\n[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master\n[node-image]: https://img.shields.io/node/v/depd.svg\n[node-url]: http://nodejs.org/download/\n[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg\n[gratipay-url]: https://www.gratipay.com/dougwilson/\n", + "readmeFilename": "Readme.md", "bugs": { "url": "https://github.com/dougwilson/nodejs-depd/issues" }, - "homepage": "https://github.com/dougwilson/nodejs-depd", "_id": "depd@1.0.1", - "_shasum": "80aec64c9d6d97e65cc2a9caa93c0aa6abf73aaa", - "_from": "depd@~1.0.0", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], - "dist": { - "shasum": "80aec64c9d6d97e65cc2a9caa93c0aa6abf73aaa", - "tarball": "http://registry.npmjs.org/depd/-/depd-1.0.1.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/depd/-/depd-1.0.1.tgz" + "_from": "depd@~1.0.1" } diff --git a/server/node_modules/express/node_modules/escape-html/.npmignore b/server/node_modules/express/node_modules/escape-html/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/escape-html/Makefile b/server/node_modules/express/node_modules/escape-html/Makefile old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/escape-html/Readme.md b/server/node_modules/express/node_modules/escape-html/Readme.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/escape-html/component.json b/server/node_modules/express/node_modules/escape-html/component.json old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/escape-html/index.js b/server/node_modules/express/node_modules/escape-html/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/escape-html/package.json b/server/node_modules/express/node_modules/escape-html/package.json old mode 100755 new mode 100644 index fefdb4e2..5e5afeb1 --- a/server/node_modules/express/node_modules/escape-html/package.json +++ b/server/node_modules/express/node_modules/escape-html/package.json @@ -18,29 +18,15 @@ "type": "git", "url": "https://github.com/component/escape-html.git" }, + "readme": "\n# escape-html\n\n Escape HTML entities\n\n## Example\n\n```js\nvar escape = require('escape-html');\nescape(str);\n```\n\n## License\n\n MIT", + "readmeFilename": "Readme.md", "bugs": { "url": "https://github.com/component/escape-html/issues" }, - "homepage": "https://github.com/component/escape-html", "_id": "escape-html@1.0.1", "dist": { - "shasum": "181a286ead397a39a92857cfb1d43052e356bff0", - "tarball": "http://registry.npmjs.org/escape-html/-/escape-html-1.0.1.tgz" + "shasum": "777cf0da92d25aa00e7a1583bcd29fd16d71343a" }, "_from": "escape-html@1.0.1", - "_npmVersion": "1.3.15", - "_npmUser": { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - } - ], - "directories": {}, - "_shasum": "181a286ead397a39a92857cfb1d43052e356bff0", - "_resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.1.tgz", - "readme": "ERROR: No README data found!" + "_resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.1.tgz" } diff --git a/server/node_modules/express/node_modules/etag/HISTORY.md b/server/node_modules/express/node_modules/etag/HISTORY.md old mode 100755 new mode 100644 index 10cf5040..e3192fce --- a/server/node_modules/express/node_modules/etag/HISTORY.md +++ b/server/node_modules/express/node_modules/etag/HISTORY.md @@ -1,3 +1,10 @@ +1.6.0 / 2015-05-10 +================== + + * Improve support for JXcore + * Remove requirement of `atime` in the stats object + * Support "fake" stats objects in environments without `fs` + 1.5.1 / 2014-11-19 ================== diff --git a/server/node_modules/express/node_modules/etag/LICENSE b/server/node_modules/express/node_modules/etag/LICENSE old mode 100755 new mode 100644 index b7dce6cf..142ede38 --- a/server/node_modules/express/node_modules/etag/LICENSE +++ b/server/node_modules/express/node_modules/etag/LICENSE @@ -1,6 +1,6 @@ (The MIT License) -Copyright (c) 2014 Douglas Christopher Wilson +Copyright (c) 2014-2015 Douglas Christopher Wilson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/server/node_modules/express/node_modules/etag/README.md b/server/node_modules/express/node_modules/etag/README.md old mode 100755 new mode 100644 index 68c16d5c..21c39c80 --- a/server/node_modules/express/node_modules/etag/README.md +++ b/server/node_modules/express/node_modules/etag/README.md @@ -51,9 +51,18 @@ $ npm test ```bash $ npm run-script bench -> etag@1.5.1 bench nodejs-etag +> etag@1.6.0 bench nodejs-etag > node benchmark/index.js + http_parser@1.0 + node@0.10.33 + v8@3.14.5.9 + ares@1.9.0-DEV + uv@0.10.29 + zlib@1.2.3 + modules@11 + openssl@1.0.1j + > node benchmark/body0-100b.js 100B body @@ -129,13 +138,13 @@ $ npm run-script bench [MIT](LICENSE) -[npm-image]: https://img.shields.io/npm/v/etag.svg?style=flat +[npm-image]: https://img.shields.io/npm/v/etag.svg [npm-url]: https://npmjs.org/package/etag -[node-version-image]: https://img.shields.io/node/v/etag.svg?style=flat +[node-version-image]: https://img.shields.io/node/v/etag.svg [node-version-url]: http://nodejs.org/download/ -[travis-image]: https://img.shields.io/travis/jshttp/etag.svg?style=flat +[travis-image]: https://img.shields.io/travis/jshttp/etag/master.svg [travis-url]: https://travis-ci.org/jshttp/etag -[coveralls-image]: https://img.shields.io/coveralls/jshttp/etag.svg?style=flat +[coveralls-image]: https://img.shields.io/coveralls/jshttp/etag/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master -[downloads-image]: https://img.shields.io/npm/dm/etag.svg?style=flat +[downloads-image]: https://img.shields.io/npm/dm/etag.svg [downloads-url]: https://npmjs.org/package/etag diff --git a/server/node_modules/express/node_modules/etag/index.js b/server/node_modules/express/node_modules/etag/index.js old mode 100755 new mode 100644 index bb05eb7e..568e5d67 --- a/server/node_modules/express/node_modules/etag/index.js +++ b/server/node_modules/express/node_modules/etag/index.js @@ -1,6 +1,6 @@ /*! * etag - * Copyright(c) 2014 Douglas Christopher Wilson + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ @@ -73,18 +73,13 @@ function etag(entity, options) { */ function isstats(obj) { - // not even an object - if (obj === null || typeof obj !== 'object') { - return false - } - // genuine fs.Stats - if (obj instanceof Stats) { + if (typeof Stats === 'function' && obj instanceof Stats) { return true } // quack quack - return 'atime' in obj && toString.call(obj.atime) === '[object Date]' + return obj && typeof obj === 'object' && 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && 'ino' in obj && typeof obj.ino === 'number' diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/.npmignore b/server/node_modules/express/node_modules/etag/node_modules/crc/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/LICENSE b/server/node_modules/express/node_modules/etag/node_modules/crc/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/README.md b/server/node_modules/express/node_modules/etag/node_modules/crc/README.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc.js b/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc1.js b/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc1.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16.js b/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_ccitt.js b/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_ccitt.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_modbus.js b/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_modbus.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc24.js b/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc24.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc32.js b/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc32.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8.js b/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8_1wire.js b/server/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8_1wire.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/lib/create.js b/server/node_modules/express/node_modules/etag/node_modules/crc/lib/create.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/lib/hex.js b/server/node_modules/express/node_modules/etag/node_modules/crc/lib/hex.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/lib/index.js b/server/node_modules/express/node_modules/etag/node_modules/crc/lib/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/etag/node_modules/crc/package.json b/server/node_modules/express/node_modules/etag/node_modules/crc/package.json old mode 100755 new mode 100644 index 1b2418aa..5dc5008e --- a/server/node_modules/express/node_modules/etag/node_modules/crc/package.json +++ b/server/node_modules/express/node_modules/etag/node_modules/crc/package.json @@ -33,25 +33,12 @@ "url": "git://github.com/alexgorbatchev/node-crc.git" }, "license": "MIT", - "gitHead": "71caf362b061992bfe4ca8706ee264e764d2e88e", + "readme": "# crc\n\n[![GitTip](http://img.shields.io/gittip/alexgorbatchev.svg?style=flat)](https://www.gittip.com/alexgorbatchev/)\n[![Dependency status](http://img.shields.io/david/alexgorbatchev/node-crc.svg?style=flat)](https://david-dm.org/alexgorbatchev/node-crc)\n[![devDependency Status](http://img.shields.io/david/dev/alexgorbatchev/node-crc.svg?style=flat)](https://david-dm.org/alexgorbatchev/node-crc#info=devDependencies)\n[![Build Status](http://img.shields.io/travis/alexgorbatchev/node-crc.svg?style=flat&branch=master)](https://travis-ci.org/alexgorbatchev/node-crc)\n\n[![NPM](https://nodei.co/npm/crc.svg?style=flat)](https://npmjs.org/package/node-crc)\n\nModule for calculating Cyclic Redundancy Check (CRC).\n\n## Features\n\n* Full test suite comparing values against reference `pycrc` implementation.\n* Version 3.x is 3x to 4x faster than version 2.x.\n* Pure JavaScript implementation, no dependencies.\n* Provides CRC Tables for optimized calculations.\n* Provides support for the following CRC algorithms:\n * CRC1 `crc.crc1(…)`\n * CRC8 `crc.crc8(…)`\n * CRC8 1-Wire `crc.crc81wire(…)`\n * CRC16 `crc.crc16(…)`\n * CRC16 CCITT `crc.crc16ccitt(…)`\n * CRC16 Modbus `crc.crc16modbus(…)`\n * CRC24 `crc.crc24(…)`\n * CRC32 `crc.crc32(…)`\n\n## IMPORTANT\n\nIf you've used `crc` module prior to version 2.x, you might have some inconsistentcies with the current implementation because it relied on very old code and wasn't checked against reference implementation. If you upgrading from 1.x, please take special care.\n\n## Support\n\n Please support me on [GitTip](https://www.gittip.com/alexgorbatchev/). I've spend days developing and grooming this module and hope to spend more time. If you have bitcoin, please use the QR code or this wallet address [`1CZyBREeHTmy8C5zVGHZHPwqBuWFmEuUCQ`](https://blockchain.info/address/1CZyBREeHTmy8C5zVGHZHPwqBuWFmEuUCQ):\n\n## Installation\n\n npm install crc\n\n## Running tests\n\n $ npm install\n $ npm test\n\n## Usage Example\n\nCalculate a CRC32:\n\n var crc = require('crc');\n\n crc.crc32('hello').toString(16);\n # => \"3610a686\"\n\nCalculate a CRC32 of a file:\n\n crc.crc32(fs.readFileSync('README.md', 'utf8')).toString(16);\n # => \"127ad531\"\n\nOr using a `Buffer`:\n\n crc.crc32(fs.readFileSync('README.md')).toString(16);\n # => \"127ad531\"\n\nIncrementally calculate a CRC32:\n\n value = crc32('one');\n value = crc32('two', value);\n value = crc32('three', value);\n value.toString(16);\n # => \"09e1c092\"\n\n## Thanks!\n\n[pycrc](http://www.tty1.net/pycrc/) library is which the source of all of the CRC tables.\n\n# License\n\nThe MIT License (MIT)\n\nCopyright (c) 2014 Alex Gorbatchev\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n", + "readmeFilename": "README.md", "_id": "crc@3.2.1", - "_shasum": "5d9c8fb77a245cd5eca291e5d2d005334bab0082", - "_from": "crc@3.2.1", - "_npmVersion": "1.4.13", - "_npmUser": { - "name": "alexgorbatchev", - "email": "alex.gorbatchev@gmail.com" - }, - "maintainers": [ - { - "name": "alexgorbatchev", - "email": "alex.gorbatchev@gmail.com" - } - ], "dist": { - "shasum": "5d9c8fb77a245cd5eca291e5d2d005334bab0082", - "tarball": "http://registry.npmjs.org/crc/-/crc-3.2.1.tgz" + "shasum": "b99ed5c7165d6ad1bd269aa2274f28dd0ba2df01" }, - "directories": {}, + "_from": "crc@3.2.1", "_resolved": "https://registry.npmjs.org/crc/-/crc-3.2.1.tgz" } diff --git a/server/node_modules/express/node_modules/etag/package.json b/server/node_modules/express/node_modules/etag/package.json old mode 100755 new mode 100644 index 13f0b417..d2312c90 --- a/server/node_modules/express/node_modules/etag/package.json +++ b/server/node_modules/express/node_modules/etag/package.json @@ -1,7 +1,7 @@ { "name": "etag", "description": "Create simple ETags", - "version": "1.5.1", + "version": "1.6.0", "contributors": [ { "name": "Douglas Christopher Wilson", @@ -20,7 +20,7 @@ ], "repository": { "type": "git", - "url": "https://github.com/jshttp/etag" + "url": "git://github.com/jshttp/etag" }, "dependencies": { "crc": "3.2.1" @@ -28,13 +28,14 @@ "devDependencies": { "benchmark": "1.0.0", "beautify-benchmark": "0.2.4", - "istanbul": "0.3.2", + "istanbul": "0.3.9", "mocha": "~1.21.4", - "seedrandom": "~2.3.6" + "seedrandom": "2.3.11" }, "files": [ "LICENSE", "HISTORY.md", + "README.md", "index.js" ], "engines": { @@ -46,29 +47,11 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" }, - "gitHead": "27335e2265388109e50a9f037452081dc8a8260f", + "readme": "# etag\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nCreate simple ETags\n\n## Installation\n\n```sh\n$ npm install etag\n```\n\n## API\n\n```js\nvar etag = require('etag')\n```\n\n### etag(entity, [options])\n\nGenerate a strong ETag for the given entity. This should be the complete\nbody of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By\ndefault, a strong ETag is generated except for `fs.Stats`, which will\ngenerate a weak ETag (this can be overwritten by `options.weak`).\n\n```js\nres.setHeader('ETag', etag(body))\n```\n\n#### Options\n\n`etag` accepts these properties in the options object.\n\n##### weak\n\nSpecifies if a \"strong\" or a \"weak\" ETag will be generated. The ETag can only\nreally be a strong as the given input.\n\n## Testing\n\n```sh\n$ npm test\n```\n\n## Benchmark\n\n```bash\n$ npm run-script bench\n\n> etag@1.6.0 bench nodejs-etag\n> node benchmark/index.js\n\n http_parser@1.0\n node@0.10.33\n v8@3.14.5.9\n ares@1.9.0-DEV\n uv@0.10.29\n zlib@1.2.3\n modules@11\n openssl@1.0.1j\n\n> node benchmark/body0-100b.js\n\n 100B body\n\n 1 test completed.\n 2 tests completed.\n 3 tests completed.\n 4 tests completed.\n\n buffer - strong x 425,007 ops/sec ±1.47% (184 runs sampled)\n* buffer - weak x 1,009,859 ops/sec ±0.18% (197 runs sampled)\n string - strong x 442,096 ops/sec ±1.20% (181 runs sampled)\n string - weak x 325,063 ops/sec ±0.31% (192 runs sampled)\n\n> node benchmark/body1-1kb.js\n\n 1KB body\n\n 1 test completed.\n 2 tests completed.\n 3 tests completed.\n 4 tests completed.\n\n buffer - strong x 263,069 ops/sec ±1.60% (190 runs sampled)\n* buffer - weak x 295,732 ops/sec ±0.43% (199 runs sampled)\n string - strong x 274,822 ops/sec ±1.15% (191 runs sampled)\n string - weak x 169,473 ops/sec ±1.59% (194 runs sampled)\n\n> node benchmark/body2-5kb.js\n\n 5KB body\n\n 1 test completed.\n 2 tests completed.\n 3 tests completed.\n 4 tests completed.\n\n buffer - strong x 104,299 ops/sec ±0.60% (193 runs sampled)\n* buffer - weak x 108,126 ops/sec ±0.65% (196 runs sampled)\n string - strong x 101,736 ops/sec ±0.78% (194 runs sampled)\n string - weak x 101,266 ops/sec ±0.85% (192 runs sampled)\n\n> node benchmark/body3-10kb.js\n\n 10KB body\n\n 1 test completed.\n 2 tests completed.\n 3 tests completed.\n 4 tests completed.\n\n buffer - strong x 59,007 ops/sec ±0.29% (198 runs sampled)\n* buffer - weak x 60,968 ops/sec ±0.48% (197 runs sampled)\n string - strong x 51,873 ops/sec ±1.78% (178 runs sampled)\n string - weak x 52,307 ops/sec ±2.63% (193 runs sampled)\n\n> node benchmark/body4-100kb.js\n\n 100KB body\n\n 1 test completed.\n 2 tests completed.\n 3 tests completed.\n 4 tests completed.\n\n buffer - strong x 6,712 ops/sec ±0.11% (198 runs sampled)\n* buffer - weak x 6,716 ops/sec ±0.50% (196 runs sampled)\n string - strong x 6,397 ops/sec ±0.36% (196 runs sampled)\n string - weak x 6,635 ops/sec ±0.15% (198 runs sampled)\n```\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/etag.svg\n[npm-url]: https://npmjs.org/package/etag\n[node-version-image]: https://img.shields.io/node/v/etag.svg\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/etag/master.svg\n[travis-url]: https://travis-ci.org/jshttp/etag\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/etag/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/etag.svg\n[downloads-url]: https://npmjs.org/package/etag\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/etag/issues" }, - "homepage": "https://github.com/jshttp/etag", - "_id": "etag@1.5.1", - "_shasum": "54c50de04ee42695562925ac566588291be7e9ea", - "_from": "etag@~1.5.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], - "dist": { - "shasum": "54c50de04ee42695562925ac566588291be7e9ea", - "tarball": "http://registry.npmjs.org/etag/-/etag-1.5.1.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/etag/-/etag-1.5.1.tgz" + "_id": "etag@1.6.0", + "_from": "etag@~1.6.0" } diff --git a/server/node_modules/express/node_modules/finalhandler/HISTORY.md b/server/node_modules/express/node_modules/finalhandler/HISTORY.md old mode 100755 new mode 100644 index 2c7e1ef9..492c62fb --- a/server/node_modules/express/node_modules/finalhandler/HISTORY.md +++ b/server/node_modules/express/node_modules/finalhandler/HISTORY.md @@ -1,3 +1,28 @@ +0.3.6 / 2015-05-11 +================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + +0.3.5 / 2015-04-22 +================== + + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + +0.3.4 / 2015-03-15 +================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.3.3 / 2015-01-01 +================== + + * deps: debug@~2.1.1 + * deps: on-finished@~2.2.0 + 0.3.2 / 2014-10-22 ================== diff --git a/server/node_modules/express/node_modules/finalhandler/LICENSE b/server/node_modules/express/node_modules/finalhandler/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/finalhandler/README.md b/server/node_modules/express/node_modules/finalhandler/README.md old mode 100755 new mode 100644 index 2015ac0c..6b171d47 --- a/server/node_modules/express/node_modules/finalhandler/README.md +++ b/server/node_modules/express/node_modules/finalhandler/README.md @@ -121,13 +121,13 @@ function logerror(err) { [MIT](LICENSE) -[npm-image]: https://img.shields.io/npm/v/finalhandler.svg?style=flat +[npm-image]: https://img.shields.io/npm/v/finalhandler.svg [npm-url]: https://npmjs.org/package/finalhandler -[node-image]: https://img.shields.io/node/v/finalhandler.svg?style=flat +[node-image]: https://img.shields.io/node/v/finalhandler.svg [node-url]: http://nodejs.org/download/ -[travis-image]: https://img.shields.io/travis/pillarjs/finalhandler.svg?style=flat +[travis-image]: https://img.shields.io/travis/pillarjs/finalhandler.svg [travis-url]: https://travis-ci.org/pillarjs/finalhandler -[coveralls-image]: https://img.shields.io/coveralls/pillarjs/finalhandler.svg?style=flat +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/finalhandler.svg [coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master -[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg?style=flat +[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg [downloads-url]: https://npmjs.org/package/finalhandler diff --git a/server/node_modules/express/node_modules/finalhandler/index.js b/server/node_modules/express/node_modules/finalhandler/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/finalhandler/package.json b/server/node_modules/express/node_modules/finalhandler/package.json old mode 100755 new mode 100644 index fc73a8a5..8f7425eb --- a/server/node_modules/express/node_modules/finalhandler/package.json +++ b/server/node_modules/express/node_modules/finalhandler/package.json @@ -1,7 +1,7 @@ { "name": "finalhandler", "description": "Node.js final http responder", - "version": "0.3.2", + "version": "0.3.6", "author": { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" @@ -9,19 +9,18 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/pillarjs/finalhandler" + "url": "git://github.com/pillarjs/finalhandler" }, "dependencies": { - "debug": "~2.1.0", + "debug": "~2.2.0", "escape-html": "1.0.1", - "on-finished": "~2.1.1" + "on-finished": "~2.2.1" }, "devDependencies": { - "istanbul": "0.3.2", - "mocha": "~2.0.0", + "istanbul": "0.3.9", + "mocha": "~2.2.4", "readable-stream": "~1.0.33", - "should": "~4.1.0", - "supertest": "~0.14.0" + "supertest": "~0.15.0" }, "files": [ "LICENSE", @@ -36,45 +35,15 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" }, - "gitHead": "1dc292faf576fade3b0218caab39060f4da5fe9c", + "readme": "# finalhandler\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-image]][node-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nNode.js function to invoke as the final step to respond to HTTP request.\n\n## Installation\n\n```sh\n$ npm install finalhandler\n```\n\n## API\n\n```js\nvar finalhandler = require('finalhandler')\n```\n\n### finalhandler(req, res, [options])\n\nReturns function to be invoked as the final step for the given `req` and `res`.\nThis function is to be invoked as `fn(err)`. If `err` is falsy, the handler will\nwrite out a 404 response to the `res`. If it is truthy, an error response will\nbe written out to the `res`, and `res.statusCode` is set from `err.status`.\n\nThe final handler will also unpipe anything from `req` when it is invoked.\n\n#### options.env\n\nBy default, the environment is determined by `NODE_ENV` variable, but it can be\noverridden by this option.\n\n#### options.onerror\n\nProvide a function to be called with the `err` when it exists. Can be used for\nwriting errors to a central location without excessive function generation. Called\nas `onerror(err, req, res)`.\n\n## Examples\n\n### always 404\n\n```js\nvar finalhandler = require('finalhandler')\nvar http = require('http')\n\nvar server = http.createServer(function (req, res) {\n var done = finalhandler(req, res)\n done()\n})\n\nserver.listen(3000)\n```\n\n### perform simple action\n\n```js\nvar finalhandler = require('finalhandler')\nvar fs = require('fs')\nvar http = require('http')\n\nvar server = http.createServer(function (req, res) {\n var done = finalhandler(req, res)\n\n fs.readFile('index.html', function (err, buf) {\n if (err) return done(err)\n res.setHeader('Content-Type', 'text/html')\n res.end(buf)\n })\n})\n\nserver.listen(3000)\n```\n\n### use with middleware-style functions\n\n```js\nvar finalhandler = require('finalhandler')\nvar http = require('http')\nvar serveStatic = require('serve-static')\n\nvar serve = serveStatic('public')\n\nvar server = http.createServer(function (req, res) {\n var done = finalhandler(req, res)\n serve(req, res, done)\n})\n\nserver.listen(3000)\n```\n\n### keep log of all errors\n\n```js\nvar finalhandler = require('finalhandler')\nvar fs = require('fs')\nvar http = require('http')\n\nvar server = http.createServer(function (req, res) {\n var done = finalhandler(req, res, {onerror: logerror})\n\n fs.readFile('index.html', function (err, buf) {\n if (err) return done(err)\n res.setHeader('Content-Type', 'text/html')\n res.end(buf)\n })\n})\n\nserver.listen(3000)\n\nfunction logerror(err) {\n console.error(err.stack || err.toString())\n}\n```\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/finalhandler.svg\n[npm-url]: https://npmjs.org/package/finalhandler\n[node-image]: https://img.shields.io/node/v/finalhandler.svg\n[node-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/pillarjs/finalhandler.svg\n[travis-url]: https://travis-ci.org/pillarjs/finalhandler\n[coveralls-image]: https://img.shields.io/coveralls/pillarjs/finalhandler.svg\n[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg\n[downloads-url]: https://npmjs.org/package/finalhandler\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/pillarjs/finalhandler/issues" }, - "homepage": "https://github.com/pillarjs/finalhandler", - "_id": "finalhandler@0.3.2", - "_shasum": "7b389b0fd3647a6f90bd564e22624bf8a4a77fb5", - "_from": "finalhandler@0.3.2", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "shtylman", - "email": "shtylman@gmail.com" - }, - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "fishrock123", - "email": "fishrock123@rocketmail.com" - } - ], + "_id": "finalhandler@0.3.6", "dist": { - "shasum": "7b389b0fd3647a6f90bd564e22624bf8a4a77fb5", - "tarball": "http://registry.npmjs.org/finalhandler/-/finalhandler-0.3.2.tgz" + "shasum": "bff149310534a66de70db21bfe568af11f10a434" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-0.3.2.tgz" + "_from": "finalhandler@0.3.6", + "_resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-0.3.6.tgz" } diff --git a/server/node_modules/express/node_modules/fresh/HISTORY.md b/server/node_modules/express/node_modules/fresh/HISTORY.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/fresh/LICENSE b/server/node_modules/express/node_modules/fresh/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/fresh/README.md b/server/node_modules/express/node_modules/fresh/README.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/fresh/index.js b/server/node_modules/express/node_modules/fresh/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/fresh/package.json b/server/node_modules/express/node_modules/fresh/package.json old mode 100755 new mode 100644 index a1535225..076f4da1 --- a/server/node_modules/express/node_modules/fresh/package.json +++ b/server/node_modules/express/node_modules/fresh/package.json @@ -16,7 +16,7 @@ ], "repository": { "type": "git", - "url": "https://github.com/jshttp/fresh" + "url": "git://github.com/jshttp/fresh" }, "devDependencies": { "istanbul": "0", @@ -36,42 +36,15 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --require should", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot --require should" }, - "gitHead": "8440a4ca75fb091dec06e88654b3b1c31d7e7164", + "readme": "# fresh\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nHTTP response freshness testing\n\n## Installation\n\n```\n$ npm install fresh\n```\n\n## API\n\n```js\nvar fresh = require('fresh')\n```\n\n### fresh(req, res)\n\n Check freshness of `req` and `res` headers.\n\n When the cache is \"fresh\" __true__ is returned,\n otherwise __false__ is returned to indicate that\n the cache is now stale.\n\n## Example\n\n```js\nvar req = { 'if-none-match': 'tobi' };\nvar res = { 'etag': 'luna' };\nfresh(req, res);\n// => false\n\nvar req = { 'if-none-match': 'tobi' };\nvar res = { 'etag': 'tobi' };\nfresh(req, res);\n// => true\n```\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/fresh.svg?style=flat\n[npm-url]: https://npmjs.org/package/fresh\n[node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/fresh.svg?style=flat\n[travis-url]: https://travis-ci.org/jshttp/fresh\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh.svg?style=flat\n[coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/fresh.svg?style=flat\n[downloads-url]: https://npmjs.org/package/fresh\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/fresh/issues" }, - "homepage": "https://github.com/jshttp/fresh", "_id": "fresh@0.2.4", - "_shasum": "3582499206c9723714190edd74b4604feb4a614c", - "_from": "fresh@0.2.4", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "jonathanong", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - } - ], "dist": { - "shasum": "3582499206c9723714190edd74b4604feb4a614c", - "tarball": "http://registry.npmjs.org/fresh/-/fresh-0.2.4.tgz" + "shasum": "691263b269f2dec1d7e8f83f974bae44bf6609c8" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.2.4.tgz", - "readme": "ERROR: No README data found!" + "_from": "fresh@0.2.4", + "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.2.4.tgz" } diff --git a/server/node_modules/express/node_modules/media-typer/HISTORY.md b/server/node_modules/express/node_modules/media-typer/HISTORY.md deleted file mode 100755 index 62c20031..00000000 --- a/server/node_modules/express/node_modules/media-typer/HISTORY.md +++ /dev/null @@ -1,22 +0,0 @@ -0.3.0 / 2014-09-07 -================== - - * Support Node.js 0.6 - * Throw error when parameter format invalid on parse - -0.2.0 / 2014-06-18 -================== - - * Add `typer.format()` to format media types - -0.1.0 / 2014-06-17 -================== - - * Accept `req` as argument to `parse` - * Accept `res` as argument to `parse` - * Parse media type with extra LWS between type and first parameter - -0.0.0 / 2014-06-13 -================== - - * Initial implementation diff --git a/server/node_modules/express/node_modules/media-typer/LICENSE b/server/node_modules/express/node_modules/media-typer/LICENSE deleted file mode 100755 index b7dce6cf..00000000 --- a/server/node_modules/express/node_modules/media-typer/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 Douglas Christopher Wilson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/express/node_modules/media-typer/README.md b/server/node_modules/express/node_modules/media-typer/README.md deleted file mode 100755 index d8df6234..00000000 --- a/server/node_modules/express/node_modules/media-typer/README.md +++ /dev/null @@ -1,81 +0,0 @@ -# media-typer - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Simple RFC 6838 media type parser - -## Installation - -```sh -$ npm install media-typer -``` - -## API - -```js -var typer = require('media-typer') -``` - -### typer.parse(string) - -```js -var obj = typer.parse('image/svg+xml; charset=utf-8') -``` - -Parse a media type string. This will return an object with the following -properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): - - - `type`: The type of the media type (always lower case). Example: `'image'` - - - `subtype`: The subtype of the media type (always lower case). Example: `'svg'` - - - `suffix`: The suffix of the media type (always lower case). Example: `'xml'` - - - `parameters`: An object of the parameters in the media type (name of parameter always lower case). Example: `{charset: 'utf-8'}` - -### typer.parse(req) - -```js -var obj = typer.parse(req) -``` - -Parse the `content-type` header from the given `req`. Short-cut for -`typer.parse(req.headers['content-type'])`. - -### typer.parse(res) - -```js -var obj = typer.parse(res) -``` - -Parse the `content-type` header set on the given `res`. Short-cut for -`typer.parse(res.getHeader('content-type'))`. - -### typer.format(obj) - -```js -var obj = typer.format({type: 'image', subtype: 'svg', suffix: 'xml'}) -``` - -Format an object into a media type string. This will return a string of the -mime type for the given object. For the properties of the object, see the -documentation for `typer.parse(string)`. - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/media-typer.svg?style=flat -[npm-url]: https://npmjs.org/package/media-typer -[node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat -[node-version-url]: http://nodejs.org/download/ -[travis-image]: https://img.shields.io/travis/jshttp/media-typer.svg?style=flat -[travis-url]: https://travis-ci.org/jshttp/media-typer -[coveralls-image]: https://img.shields.io/coveralls/jshttp/media-typer.svg?style=flat -[coveralls-url]: https://coveralls.io/r/jshttp/media-typer -[downloads-image]: https://img.shields.io/npm/dm/media-typer.svg?style=flat -[downloads-url]: https://npmjs.org/package/media-typer diff --git a/server/node_modules/express/node_modules/media-typer/index.js b/server/node_modules/express/node_modules/media-typer/index.js deleted file mode 100755 index 07f7295e..00000000 --- a/server/node_modules/express/node_modules/media-typer/index.js +++ /dev/null @@ -1,270 +0,0 @@ -/*! - * media-typer - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7 - * - * parameter = token "=" ( token | quoted-string ) - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - * qdtext = > - * quoted-pair = "\" CHAR - * CHAR = - * TEXT = - * LWS = [CRLF] 1*( SP | HT ) - * CRLF = CR LF - * CR = - * LF = - * SP = - * SHT = - * CTL = - * OCTET = - */ -var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g; -var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/ -var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ - -/** - * RegExp to match quoted-pair in RFC 2616 - * - * quoted-pair = "\" CHAR - * CHAR = - */ -var qescRegExp = /\\([\u0000-\u007f])/g; - -/** - * RegExp to match chars that must be quoted-pair in RFC 2616 - */ -var quoteRegExp = /([\\"])/g; - -/** - * RegExp to match type in RFC 6838 - * - * type-name = restricted-name - * subtype-name = restricted-name - * restricted-name = restricted-name-first *126restricted-name-chars - * restricted-name-first = ALPHA / DIGIT - * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / - * "$" / "&" / "-" / "^" / "_" - * restricted-name-chars =/ "." ; Characters before first dot always - * ; specify a facet name - * restricted-name-chars =/ "+" ; Characters after last plus always - * ; specify a structured syntax suffix - * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z - * DIGIT = %x30-39 ; 0-9 - */ -var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ -var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ -var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; - -/** - * Module exports. - */ - -exports.format = format -exports.parse = parse - -/** - * Format object to media type. - * - * @param {object} obj - * @return {string} - * @api public - */ - -function format(obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') - } - - var parameters = obj.parameters - var subtype = obj.subtype - var suffix = obj.suffix - var type = obj.type - - if (!type || !typeNameRegExp.test(type)) { - throw new TypeError('invalid type') - } - - if (!subtype || !subtypeNameRegExp.test(subtype)) { - throw new TypeError('invalid subtype') - } - - // format as type/subtype - var string = type + '/' + subtype - - // append +suffix - if (suffix) { - if (!typeNameRegExp.test(suffix)) { - throw new TypeError('invalid suffix') - } - - string += '+' + suffix - } - - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() - - for (var i = 0; i < params.length; i++) { - param = params[i] - - if (!tokenRegExp.test(param)) { - throw new TypeError('invalid parameter name') - } - - string += '; ' + param + '=' + qstring(parameters[param]) - } - } - - return string -} - -/** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @api public - */ - -function parse(string) { - if (!string) { - throw new TypeError('argument string is required') - } - - // support req/res-like objects as argument - if (typeof string === 'object') { - string = getcontenttype(string) - } - - if (typeof string !== 'string') { - throw new TypeError('argument string is required to be a string') - } - - var index = string.indexOf(';') - var type = index !== -1 - ? string.substr(0, index) - : string - - var key - var match - var obj = splitType(type) - var params = {} - var value - - paramRegExp.lastIndex = index - - while (match = paramRegExp.exec(string)) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } - - index += match[0].length - key = match[1].toLowerCase() - value = match[2] - - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(qescRegExp, '$1') - } - - params[key] = value - } - - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') - } - - obj.parameters = params - - return obj -} - -/** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @api private - */ - -function getcontenttype(obj) { - if (typeof obj.getHeader === 'function') { - // res-like - return obj.getHeader('content-type') - } - - if (typeof obj.headers === 'object') { - // req-like - return obj.headers && obj.headers['content-type'] - } -} - -/** - * Quote a string if necessary. - * - * @param {string} val - * @return {string} - * @api private - */ - -function qstring(val) { - var str = String(val) - - // no need to quote tokens - if (tokenRegExp.test(str)) { - return str - } - - if (str.length > 0 && !textRegExp.test(str)) { - throw new TypeError('invalid parameter value') - } - - return '"' + str.replace(quoteRegExp, '\\$1') + '"' -} - -/** - * Simply "type/subtype+siffx" into parts. - * - * @param {string} string - * @return {Object} - * @api private - */ - -function splitType(string) { - var match = typeRegExp.exec(string.toLowerCase()) - - if (!match) { - throw new TypeError('invalid media type') - } - - var type = match[1] - var subtype = match[2] - var suffix - - // suffix after last + - var index = subtype.lastIndexOf('+') - if (index !== -1) { - suffix = subtype.substr(index + 1) - subtype = subtype.substr(0, index) - } - - var obj = { - type: type, - subtype: subtype, - suffix: suffix - } - - return obj -} diff --git a/server/node_modules/express/node_modules/media-typer/package.json b/server/node_modules/express/node_modules/media-typer/package.json deleted file mode 100755 index 4bd1a51b..00000000 --- a/server/node_modules/express/node_modules/media-typer/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "media-typer", - "description": "Simple RFC 6838 media type parser and formatter", - "version": "0.3.0", - "author": { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/jshttp/media-typer" - }, - "devDependencies": { - "istanbul": "0.3.2", - "mocha": "~1.21.4", - "should": "~4.0.4" - }, - "files": [ - "LICENSE", - "HISTORY.md", - "index.js" - ], - "engines": { - "node": ">= 0.6" - }, - "scripts": { - "test": "mocha --reporter spec --check-leaks --bail test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" - }, - "gitHead": "d49d41ffd0bb5a0655fa44a59df2ec0bfc835b16", - "bugs": { - "url": "https://github.com/jshttp/media-typer/issues" - }, - "homepage": "https://github.com/jshttp/media-typer", - "_id": "media-typer@0.3.0", - "_shasum": "8710d7af0aa626f8fffa1ce00168545263255748", - "_from": "media-typer@0.3.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], - "dist": { - "shasum": "8710d7af0aa626f8fffa1ce00168545263255748", - "tarball": "http://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/server/node_modules/express/node_modules/merge-descriptors/.npmignore b/server/node_modules/express/node_modules/merge-descriptors/.npmignore deleted file mode 100755 index f62e6050..00000000 --- a/server/node_modules/express/node_modules/merge-descriptors/.npmignore +++ /dev/null @@ -1,59 +0,0 @@ -# Compiled source # -################### -*.com -*.class -*.dll -*.exe -*.o -*.so - -# Packages # -############ -# it's better to unpack these files and commit the raw source -# git has its own built in compression methods -*.7z -*.dmg -*.gz -*.iso -*.jar -*.rar -*.tar -*.zip - -# Logs and databases # -###################### -*.log -*.sql -*.sqlite - -# OS generated files # -###################### -.DS_Store* -ehthumbs.db -Icon? -Thumbs.db - -# Node.js # -########### -lib-cov -*.seed -*.log -*.csv -*.dat -*.out -*.pid -*.gz - -pids -logs -results - -node_modules -npm-debug.log - -# Components # -############## - -/build -/components -/vendors \ No newline at end of file diff --git a/server/node_modules/express/node_modules/merge-descriptors/README.md b/server/node_modules/express/node_modules/merge-descriptors/README.md old mode 100755 new mode 100644 index 50cf50c0..ca4cf247 --- a/server/node_modules/express/node_modules/merge-descriptors/README.md +++ b/server/node_modules/express/node_modules/merge-descriptors/README.md @@ -1,4 +1,4 @@ -# Merge Descriptors [![Build Status](https://travis-ci.org/component/merge-descriptors.png)](https://travis-ci.org/component/merge-descriptors) +# Merge Descriptors Merge objects using descriptors. @@ -22,28 +22,13 @@ animal.name === 'jon' ### merge(destination, source) -Overwrites `destination`'s descriptors with `source`'s. +Redefines `destination`'s descriptors with `source`'s. + +### merge(destination, source, false) + +Defines `source`'s descriptors on `destination` if `destination` does not have +a descriptor by the same name. ## License -The MIT License (MIT) - -Copyright (c) 2013 Jonathan Ong me@jongleberry.com - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file +[MIT](LICENSE) diff --git a/server/node_modules/express/node_modules/merge-descriptors/component.json b/server/node_modules/express/node_modules/merge-descriptors/component.json deleted file mode 100755 index 7653906b..00000000 --- a/server/node_modules/express/node_modules/merge-descriptors/component.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "merge-descriptors", - "description": "Merge objects using descriptors", - "version": "0.0.2", - "scripts": [ - "index.js" - ], - "repo": "component/merge-descriptors", - "license": "MIT" -} \ No newline at end of file diff --git a/server/node_modules/express/node_modules/merge-descriptors/index.js b/server/node_modules/express/node_modules/merge-descriptors/index.js old mode 100755 new mode 100644 index e4e23793..5d0af3a0 --- a/server/node_modules/express/node_modules/merge-descriptors/index.js +++ b/server/node_modules/express/node_modules/merge-descriptors/index.js @@ -1,8 +1,57 @@ -module.exports = function (dest, src) { - Object.getOwnPropertyNames(src).forEach(function (name) { +/*! + * merge-descriptors + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +module.exports = merge + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty + +/** + * Merge the property descriptors of `src` into `dest` + * + * @param {object} dest Object to add descriptors to + * @param {object} src Object to clone descriptors from + * @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties + * @returns {object} Reference to dest + * @public + */ + +function merge(dest, src, redefine) { + if (!dest) { + throw new TypeError('argument dest is required') + } + + if (!src) { + throw new TypeError('argument src is required') + } + + if (redefine === undefined) { + // Default to true + redefine = true + } + + Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) { + if (!redefine && hasOwnProperty.call(dest, name)) { + // Skip desriptor + return + } + + // Copy descriptor var descriptor = Object.getOwnPropertyDescriptor(src, name) Object.defineProperty(dest, name, descriptor) }) return dest -} \ No newline at end of file +} diff --git a/server/node_modules/express/node_modules/merge-descriptors/package.json b/server/node_modules/express/node_modules/merge-descriptors/package.json old mode 100755 new mode 100644 index b1b83d4f..9ff5e5c5 --- a/server/node_modules/express/node_modules/merge-descriptors/package.json +++ b/server/node_modules/express/node_modules/merge-descriptors/package.json @@ -1,12 +1,18 @@ { "name": "merge-descriptors", "description": "Merge objects using descriptors", - "version": "0.0.2", + "version": "1.0.0", "author": { "name": "Jonathan Ong", "email": "me@jongleberry.com", "url": "http://jongleberry.com" }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], "license": "MIT", "repository": { "type": "git", @@ -15,29 +21,17 @@ "bugs": { "url": "https://github.com/component/merge-descriptors/issues" }, - "scripts": { - "test": "make test;" - }, - "homepage": "https://github.com/component/merge-descriptors", - "_id": "merge-descriptors@0.0.2", - "dist": { - "shasum": "c36a52a781437513c57275f39dd9d317514ac8c7", - "tarball": "http://registry.npmjs.org/merge-descriptors/-/merge-descriptors-0.0.2.tgz" - }, - "_from": "merge-descriptors@0.0.2", - "_npmVersion": "1.3.17", - "_npmUser": { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - } + "files": [ + "LICENSE", + "README.md", + "index.js" ], - "directories": {}, - "_shasum": "c36a52a781437513c57275f39dd9d317514ac8c7", - "_resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-0.0.2.tgz", - "readme": "ERROR: No README data found!" + "readme": "# Merge Descriptors\n\nMerge objects using descriptors.\n\n```js\nvar thing = {\n get name() {\n return 'jon'\n }\n}\n\nvar animal = {\n\n}\n\nmerge(animal, thing)\n\nanimal.name === 'jon'\n```\n\n## API\n\n### merge(destination, source)\n\nRedefines `destination`'s descriptors with `source`'s.\n\n### merge(destination, source, false)\n\nDefines `source`'s descriptors on `destination` if `destination` does not have\na descriptor by the same name.\n\n## License\n\n[MIT](LICENSE)\n", + "readmeFilename": "README.md", + "_id": "merge-descriptors@1.0.0", + "dist": { + "shasum": "f0ecc7a26ffde8e30b07248c3b2bb0d9cbeddfd1" + }, + "_from": "merge-descriptors@1.0.0", + "_resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.0.tgz" } diff --git a/server/node_modules/express/node_modules/methods/.npmignore b/server/node_modules/express/node_modules/methods/.npmignore deleted file mode 100755 index c2658d7d..00000000 --- a/server/node_modules/express/node_modules/methods/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules/ diff --git a/server/node_modules/express/node_modules/methods/History.md b/server/node_modules/express/node_modules/methods/History.md deleted file mode 100755 index d3996c2e..00000000 --- a/server/node_modules/express/node_modules/methods/History.md +++ /dev/null @@ -1,20 +0,0 @@ - -1.1.0 / 2014-07-05 -================== - - * add CONNECT - -1.0.1 / 2014-06-02 -================== - - * fix index.js to work with harmony transform - -1.0.0 / 2014-05-08 -================== - - * add PURGE. Closes #9 - -0.1.0 / 2013-10-28 -================== - - * add http.METHODS support diff --git a/server/node_modules/express/node_modules/methods/LICENSE b/server/node_modules/express/node_modules/methods/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/methods/Readme.md b/server/node_modules/express/node_modules/methods/Readme.md deleted file mode 100755 index ac0658e2..00000000 --- a/server/node_modules/express/node_modules/methods/Readme.md +++ /dev/null @@ -1,4 +0,0 @@ - -# Methods - - HTTP verbs that node core's parser supports. diff --git a/server/node_modules/express/node_modules/methods/index.js b/server/node_modules/express/node_modules/methods/index.js old mode 100755 new mode 100644 index f7e3c486..e89c7fd8 --- a/server/node_modules/express/node_modules/methods/index.js +++ b/server/node_modules/express/node_modules/methods/index.js @@ -1,6 +1,7 @@ var http = require('http'); +/* istanbul ignore next: implementation differs on version */ if (http.METHODS) { module.exports = http.METHODS.map(function(method){ diff --git a/server/node_modules/express/node_modules/methods/package.json b/server/node_modules/express/node_modules/methods/package.json old mode 100755 new mode 100644 index 8d1c1988..f84a340e --- a/server/node_modules/express/node_modules/methods/package.json +++ b/server/node_modules/express/node_modules/methods/package.json @@ -1,58 +1,57 @@ { "name": "methods", - "version": "1.1.0", "description": "HTTP methods that node supports", - "main": "index.js", + "version": "1.1.1", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/jshttp/methods" + }, + "devDependencies": { + "istanbul": "0.3", + "mocha": "1" + }, + "files": [ + "index.js", + "HISTORY.md", + "LICENSE" + ], + "engines": { + "node": ">= 0.6" + }, "scripts": { - "test": "./node_modules/mocha/bin/mocha" + "test": "mocha --reporter spec", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "browser": { + "http": false }, "keywords": [ "http", "methods" ], - "author": { - "name": "TJ Holowaychuk" - }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/node-methods.git" - }, - "devDependencies": { - "mocha": "1.17.x" - }, - "gitHead": "2a4dd325d18436c33356e6be19e32e08a7c877ab", + "readme": "# Methods\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\n HTTP verbs that node core's parser supports.\n\n\n## Install\n\n```bash\n$ npm install methods\n```\n\n## API\n\n```js\nvar methods = require('methods')\n```\n\n### methods\n\nThis is an array of lower-case method names that Node.js supports.\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/methods.svg?style=flat\n[npm-url]: https://npmjs.org/package/methods\n[node-version-image]: https://img.shields.io/node/v/methods.svg?style=flat\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/methods.svg?style=flat\n[travis-url]: https://travis-ci.org/jshttp/methods\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/methods.svg?style=flat\n[coveralls-url]: https://coveralls.io/r/jshttp/methods?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/methods.svg?style=flat\n[downloads-url]: https://npmjs.org/package/methods\n", + "readmeFilename": "README.md", "bugs": { - "url": "https://github.com/visionmedia/node-methods/issues" + "url": "https://github.com/jshttp/methods/issues" }, - "homepage": "https://github.com/visionmedia/node-methods", - "_id": "methods@1.1.0", - "_shasum": "5dca4ee12df52ff3b056145986a8f01cbc86436f", - "_from": "methods@1.1.0", - "_npmVersion": "1.4.16", - "_npmUser": { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "jonathanong", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - } - ], - "dist": { - "shasum": "5dca4ee12df52ff3b056145986a8f01cbc86436f", - "tarball": "http://registry.npmjs.org/methods/-/methods-1.1.0.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/methods/-/methods-1.1.0.tgz", - "readme": "ERROR: No README data found!" + "_id": "methods@1.1.1", + "_from": "methods@~1.1.1" } diff --git a/server/node_modules/express/node_modules/methods/test/methods.js b/server/node_modules/express/node_modules/methods/test/methods.js deleted file mode 100755 index 527beaba..00000000 --- a/server/node_modules/express/node_modules/methods/test/methods.js +++ /dev/null @@ -1,33 +0,0 @@ -var http = require('http'); -var assert = require('assert'); -var methods = require('..'); - -describe('methods', function() { - - if (http.METHODS) { - - it('is a lowercased http.METHODS', function() { - var lowercased = http.METHODS.map(function(method) { - return method.toLowerCase(); - }); - assert.deepEqual(lowercased, methods); - }); - - } else { - - it('contains GET, POST, PUT, and DELETE', function() { - assert.notEqual(methods.indexOf('get'), -1); - assert.notEqual(methods.indexOf('post'), -1); - assert.notEqual(methods.indexOf('put'), -1); - assert.notEqual(methods.indexOf('delete'), -1); - }); - - it('is all lowercase', function() { - for (var i = 0; i < methods.length; i ++) { - assert(methods[i], methods[i].toLowerCase(), methods[i] + " isn't all lowercase"); - } - }); - - } - -}); diff --git a/server/node_modules/express/node_modules/on-finished/HISTORY.md b/server/node_modules/express/node_modules/on-finished/HISTORY.md old mode 100755 new mode 100644 index 1a4063dc..88f1a0c8 --- a/server/node_modules/express/node_modules/on-finished/HISTORY.md +++ b/server/node_modules/express/node_modules/on-finished/HISTORY.md @@ -1,3 +1,13 @@ +2.2.1 / 2015-04-22 +================== + + * Fix `isFinished(req)` when data buffered + +2.2.0 / 2014-12-22 +================== + + * Add message object to callback arguments + 2.1.1 / 2014-10-22 ================== diff --git a/server/node_modules/express/node_modules/on-finished/LICENSE b/server/node_modules/express/node_modules/on-finished/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/on-finished/README.md b/server/node_modules/express/node_modules/on-finished/README.md old mode 100755 new mode 100644 index 6fb0e4d4..b58ebd09 --- a/server/node_modules/express/node_modules/on-finished/README.md +++ b/server/node_modules/express/node_modules/on-finished/README.md @@ -24,14 +24,18 @@ var onFinished = require('on-finished') Attach a listener to listen for the response to finish. The listener will be invoked only once when the response finished. If the response finished -to to an error, the first argument will contain the error. +to to an error, the first argument will contain the error. If the response +has already finished, the listener will be invoked. Listening to the end of a response would be used to close things associated with the response, like open files. +Listener is invoked as `listener(err, res)`. + ```js -onFinished(res, function (err) { +onFinished(res, function (err, res) { // clean up open fds, etc. + // err contains the error is request error'd }) ``` @@ -39,11 +43,14 @@ onFinished(res, function (err) { Attach a listener to listen for the request to finish. The listener will be invoked only once when the request finished. If the request finished -to to an error, the first argument will contain the error. +to to an error, the first argument will contain the error. If the request +has already finished, the listener will be invoked. Listening to the end of a request would be used to know when to continue after reading the data. +Listener is invoked as `listener(err, req)`. + ```js var data = '' @@ -52,7 +59,7 @@ res.on('data', function (str) { data += str }) -onFinished(req, function (err) { +onFinished(req, function (err, req) { // data is read unless there is err }) ``` @@ -90,13 +97,13 @@ http.createServer(function onRequest(req, res) { [MIT](LICENSE) -[npm-image]: https://img.shields.io/npm/v/on-finished.svg?style=flat +[npm-image]: https://img.shields.io/npm/v/on-finished.svg [npm-url]: https://npmjs.org/package/on-finished -[node-version-image]: https://img.shields.io/node/v/on-finished.svg?style=flat +[node-version-image]: https://img.shields.io/node/v/on-finished.svg [node-version-url]: http://nodejs.org/download/ -[travis-image]: https://img.shields.io/travis/jshttp/on-finished.svg?style=flat +[travis-image]: https://img.shields.io/travis/jshttp/on-finished/master.svg [travis-url]: https://travis-ci.org/jshttp/on-finished -[coveralls-image]: https://img.shields.io/coveralls/jshttp/on-finished.svg?style=flat +[coveralls-image]: https://img.shields.io/coveralls/jshttp/on-finished/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master -[downloads-image]: https://img.shields.io/npm/dm/on-finished.svg?style=flat +[downloads-image]: https://img.shields.io/npm/dm/on-finished.svg [downloads-url]: https://npmjs.org/package/on-finished diff --git a/server/node_modules/express/node_modules/on-finished/index.js b/server/node_modules/express/node_modules/on-finished/index.js old mode 100755 new mode 100644 index e75a7e9b..2402c761 --- a/server/node_modules/express/node_modules/on-finished/index.js +++ b/server/node_modules/express/node_modules/on-finished/index.js @@ -39,7 +39,7 @@ var defer = typeof setImmediate === 'function' function onFinished(msg, listener) { if (isFinished(msg) !== false) { - defer(listener) + defer(listener, null, msg) return msg } @@ -67,7 +67,7 @@ function isFinished(msg) { if (typeof msg.complete === 'boolean') { // IncomingMessage - return Boolean(!socket || msg.complete || !socket.readable) + return Boolean(!socket || !socket.readable || (msg.complete && !msg.readable)) } // don't know @@ -161,7 +161,7 @@ function createListener(msg) { listener.queue = null for (var i = 0; i < queue.length; i++) { - queue[i](err) + queue[i](err, msg) } } diff --git a/server/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE b/server/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md b/server/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js b/server/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json b/server/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json old mode 100755 new mode 100644 index af11b2ac..480be6bb --- a/server/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json +++ b/server/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json @@ -16,7 +16,7 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/jonathanong/ee-first" + "url": "git://github.com/jonathanong/ee-first" }, "devDependencies": { "istanbul": "0.3.2", @@ -31,33 +31,15 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" }, - "gitHead": "a6412004da4745941af2fc98ec30c8da570da7ea", + "readme": "# EE First\r\n\r\n[![NPM version][npm-image]][npm-url]\r\n[![Build status][travis-image]][travis-url]\r\n[![Test coverage][coveralls-image]][coveralls-url]\r\n[![License][license-image]][license-url]\r\n[![Downloads][downloads-image]][downloads-url]\r\n[![Gittip][gittip-image]][gittip-url]\r\n\r\nGet the first event in a set of event emitters and event pairs,\r\nthen clean up after itself.\r\n\r\n## Install\r\n\r\n```sh\r\n$ npm install ee-first\r\n```\r\n\r\n## API\r\n\r\n```js\r\nvar first = require('ee-first')\r\n```\r\n\r\n### first(arr, listener)\r\n\r\nInvoke `listener` on the first event from the list specified in `arr`. `arr` is\r\nan array of arrays, with each array in the format `[ee, ...event]`. `listener`\r\nwill be called only once, the first time any of the given events are emitted. If\r\n`error` is one of the listened events, then if that fires first, the `listener`\r\nwill be given the `err` argument.\r\n\r\nThe `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the\r\nfirst argument emitted from an `error` event, if applicable; `ee` is the event\r\nemitter that fired; `event` is the string event name that fired; and `args` is an\r\narray of the arguments that were emitted on the event.\r\n\r\n```js\r\nvar ee1 = new EventEmitter()\r\nvar ee2 = new EventEmitter()\r\n\r\nfirst([\r\n [ee1, 'close', 'end', 'error'],\r\n [ee2, 'error']\r\n], function (err, ee, event, args) {\r\n // listener invoked\r\n})\r\n```\r\n\r\n#### .cancel()\r\n\r\nThe group of listeners can be cancelled before being invoked and have all the event\r\nlisteners removed from the underlying event emitters.\r\n\r\n```js\r\nvar thunk = first([\r\n [ee1, 'close', 'end', 'error'],\r\n [ee2, 'error']\r\n], function (err, ee, event, args) {\r\n // listener invoked\r\n})\r\n\r\n// cancel and clean up\r\nthunk.cancel()\r\n```\r\n\r\n[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square\r\n[npm-url]: https://npmjs.org/package/ee-first\r\n[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square\r\n[github-url]: https://github.com/jonathanong/ee-first/tags\r\n[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square\r\n[travis-url]: https://travis-ci.org/jonathanong/ee-first\r\n[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square\r\n[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master\r\n[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square\r\n[license-url]: LICENSE.md\r\n[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square\r\n[downloads-url]: https://npmjs.org/package/ee-first\r\n[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square\r\n[gittip-url]: https://www.gittip.com/jonathanong/\r\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jonathanong/ee-first/issues" }, - "homepage": "https://github.com/jonathanong/ee-first", "_id": "ee-first@1.1.0", - "_shasum": "6a0d7c6221e490feefd92ec3f441c9ce8cd097f4", - "_from": "ee-first@1.1.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], "dist": { - "shasum": "6a0d7c6221e490feefd92ec3f441c9ce8cd097f4", - "tarball": "http://registry.npmjs.org/ee-first/-/ee-first-1.1.0.tgz" + "shasum": "dd68b4175286e43ab53b0003a884cc587809ca83" }, - "directories": {}, + "_from": "ee-first@1.1.0", "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.0.tgz" } diff --git a/server/node_modules/express/node_modules/on-finished/package.json b/server/node_modules/express/node_modules/on-finished/package.json old mode 100755 new mode 100644 index 85c11b31..d408d1d2 --- a/server/node_modules/express/node_modules/on-finished/package.json +++ b/server/node_modules/express/node_modules/on-finished/package.json @@ -1,7 +1,7 @@ { "name": "on-finished", "description": "Execute a callback when a request closes, finishes, or errors", - "version": "2.1.1", + "version": "2.2.1", "contributors": [ { "name": "Douglas Christopher Wilson", @@ -16,14 +16,14 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/jshttp/on-finished" + "url": "git://github.com/jshttp/on-finished" }, "dependencies": { "ee-first": "1.1.0" }, "devDependencies": { - "istanbul": "0.3.2", - "mocha": "~2.0.0" + "istanbul": "0.3.9", + "mocha": "~2.2.4" }, "engines": { "node": ">= 0.8" @@ -38,33 +38,11 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" }, - "gitHead": "8ec5fa639ace400b543b5bc1821ce909b9acdc03", + "readme": "# on-finished\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nExecute a callback when a request closes, finishes, or errors.\n\n## Install\n\n```sh\n$ npm install on-finished\n```\n\n## API\n\n```js\nvar onFinished = require('on-finished')\n```\n\n### onFinished(res, listener)\n\nAttach a listener to listen for the response to finish. The listener will\nbe invoked only once when the response finished. If the response finished\nto to an error, the first argument will contain the error. If the response\nhas already finished, the listener will be invoked.\n\nListening to the end of a response would be used to close things associated\nwith the response, like open files.\n\nListener is invoked as `listener(err, res)`.\n\n```js\nonFinished(res, function (err, res) {\n // clean up open fds, etc.\n // err contains the error is request error'd\n})\n```\n\n### onFinished(req, listener)\n\nAttach a listener to listen for the request to finish. The listener will\nbe invoked only once when the request finished. If the request finished\nto to an error, the first argument will contain the error. If the request\nhas already finished, the listener will be invoked.\n\nListening to the end of a request would be used to know when to continue\nafter reading the data.\n\nListener is invoked as `listener(err, req)`.\n\n```js\nvar data = ''\n\nreq.setEncoding('utf8')\nres.on('data', function (str) {\n data += str\n})\n\nonFinished(req, function (err, req) {\n // data is read unless there is err\n})\n```\n\n### onFinished.isFinished(res)\n\nDetermine if `res` is already finished. This would be useful to check and\nnot even start certain operations if the response has already finished.\n\n### onFinished.isFinished(req)\n\nDetermine if `req` is already finished. This would be useful to check and\nnot even start certain operations if the request has already finished.\n\n### Example\n\nThe following code ensures that file descriptors are always closed\nonce the response finishes.\n\n```js\nvar destroy = require('destroy')\nvar http = require('http')\nvar onFinished = require('on-finished')\n\nhttp.createServer(function onRequest(req, res) {\n var stream = fs.createReadStream('package.json')\n stream.pipe(res)\n onFinished(res, function (err) {\n destroy(stream)\n })\n})\n```\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/on-finished.svg\n[npm-url]: https://npmjs.org/package/on-finished\n[node-version-image]: https://img.shields.io/node/v/on-finished.svg\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/on-finished/master.svg\n[travis-url]: https://travis-ci.org/jshttp/on-finished\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/on-finished/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/on-finished.svg\n[downloads-url]: https://npmjs.org/package/on-finished\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/on-finished/issues" }, - "homepage": "https://github.com/jshttp/on-finished", - "_id": "on-finished@2.1.1", - "_shasum": "f82ca1c9e3a4f3286b1b9938610e5b8636bd3cb2", - "_from": "on-finished@~2.1.1", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - } - ], - "dist": { - "shasum": "f82ca1c9e3a4f3286b1b9938610e5b8636bd3cb2", - "tarball": "http://registry.npmjs.org/on-finished/-/on-finished-2.1.1.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.1.1.tgz" + "_id": "on-finished@2.2.1", + "_from": "on-finished@~2.2.1" } diff --git a/server/node_modules/express/node_modules/parseurl/.npmignore b/server/node_modules/express/node_modules/parseurl/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/parseurl/HISTORY.md b/server/node_modules/express/node_modules/parseurl/HISTORY.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/parseurl/LICENSE b/server/node_modules/express/node_modules/parseurl/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/parseurl/README.md b/server/node_modules/express/node_modules/parseurl/README.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/parseurl/index.js b/server/node_modules/express/node_modules/parseurl/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/parseurl/package.json b/server/node_modules/express/node_modules/parseurl/package.json old mode 100755 new mode 100644 index 6fbd23e9..341005fd --- a/server/node_modules/express/node_modules/parseurl/package.json +++ b/server/node_modules/express/node_modules/parseurl/package.json @@ -15,7 +15,7 @@ ], "repository": { "type": "git", - "url": "https://github.com/expressjs/parseurl" + "url": "git://github.com/expressjs/parseurl" }, "license": "MIT", "devDependencies": { @@ -31,50 +31,11 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec test/" }, - "gitHead": "03b7ccca240e2bef5df6c25797e99175d28fb2cb", + "readme": "# parseurl\n\n[![NPM version](https://badge.fury.io/js/parseurl.svg)](http://badge.fury.io/js/parseurl)\n[![Build Status](https://travis-ci.org/expressjs/parseurl.svg?branch=master)](https://travis-ci.org/expressjs/parseurl)\n[![Coverage Status](https://img.shields.io/coveralls/expressjs/parseurl.svg?branch=master)](https://coveralls.io/r/expressjs/parseurl)\n\nParse a URL with memoization.\n\n## Install\n\n```bash\n$ npm install parseurl\n```\n\n## API\n\n```js\nvar parseurl = require('parseurl')\n```\n\n### parseurl(req)\n\nParse the URL of the given request object (looks at the `req.url` property)\nand return the result. The result is the same as `url.parse` in Node.js core.\nCalling this function multiple times on the same `req` where `req.url` does\nnot change will return a cached parsed object, rather than parsing again.\n\n### parseurl.original(req)\n\nParse the original URL of the given request object and return the result.\nThis works by trying to parse `req.originalUrl` if it is a string, otherwise\nparses `req.url`. The result is the same as `url.parse` in Node.js core.\nCalling this function multiple times on the same `req` where `req.originalUrl`\ndoes not change will return a cached parsed object, rather than parsing again.\n\n## Benchmark\n\n```bash\n$ npm run-script bench\n\n> parseurl@1.3.0 bench nodejs-parseurl\n> node benchmark/index.js\n\n> node benchmark/fullurl.js\n\n Parsing URL \"http://localhost:8888/foo/bar?user=tj&pet=fluffy\"\n\n 1 test completed.\n 2 tests completed.\n 3 tests completed.\n\n fasturl x 1,290,780 ops/sec ±0.46% (195 runs sampled)\n nativeurl x 56,401 ops/sec ±0.22% (196 runs sampled)\n parseurl x 55,231 ops/sec ±0.22% (194 runs sampled)\n\n> node benchmark/pathquery.js\n\n Parsing URL \"/foo/bar?user=tj&pet=fluffy\"\n\n 1 test completed.\n 2 tests completed.\n 3 tests completed.\n\n fasturl x 1,986,668 ops/sec ±0.27% (190 runs sampled)\n nativeurl x 98,740 ops/sec ±0.21% (195 runs sampled)\n parseurl x 2,628,171 ops/sec ±0.36% (195 runs sampled)\n\n> node benchmark/samerequest.js\n\n Parsing URL \"/foo/bar?user=tj&pet=fluffy\" on same request object\n\n 1 test completed.\n 2 tests completed.\n 3 tests completed.\n\n fasturl x 2,184,468 ops/sec ±0.40% (194 runs sampled)\n nativeurl x 99,437 ops/sec ±0.71% (194 runs sampled)\n parseurl x 10,498,005 ops/sec ±0.61% (186 runs sampled)\n\n> node benchmark/simplepath.js\n\n Parsing URL \"/foo/bar\"\n\n 1 test completed.\n 2 tests completed.\n 3 tests completed.\n\n fasturl x 4,535,825 ops/sec ±0.27% (191 runs sampled)\n nativeurl x 98,769 ops/sec ±0.54% (191 runs sampled)\n parseurl x 4,164,865 ops/sec ±0.34% (192 runs sampled)\n\n> node benchmark/slash.js\n\n Parsing URL \"/\"\n\n 1 test completed.\n 2 tests completed.\n 3 tests completed.\n\n fasturl x 4,908,405 ops/sec ±0.42% (191 runs sampled)\n nativeurl x 100,945 ops/sec ±0.59% (188 runs sampled)\n parseurl x 4,333,208 ops/sec ±0.27% (194 runs sampled)\n```\n\n## License\n\n [MIT](LICENSE)\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/expressjs/parseurl/issues" }, - "homepage": "https://github.com/expressjs/parseurl", "_id": "parseurl@1.3.0", - "_shasum": "b58046db4223e145afa76009e61bac87cc2281b3", - "_from": "parseurl@~1.3.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "shtylman", - "email": "shtylman@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "mscdex", - "email": "mscdex@mscdex.net" - }, - { - "name": "fishrock123", - "email": "fishrock123@rocketmail.com" - } - ], - "dist": { - "shasum": "b58046db4223e145afa76009e61bac87cc2281b3", - "tarball": "http://registry.npmjs.org/parseurl/-/parseurl-1.3.0.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.0.tgz", - "readme": "ERROR: No README data found!" + "_from": "parseurl@~1.3.0" } diff --git a/server/node_modules/express/node_modules/path-to-regexp/.npmignore b/server/node_modules/express/node_modules/path-to-regexp/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/path-to-regexp/History.md b/server/node_modules/express/node_modules/path-to-regexp/History.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/path-to-regexp/Readme.md b/server/node_modules/express/node_modules/path-to-regexp/Readme.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/path-to-regexp/component.json b/server/node_modules/express/node_modules/path-to-regexp/component.json old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/path-to-regexp/index.js b/server/node_modules/express/node_modules/path-to-regexp/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/path-to-regexp/package.json b/server/node_modules/express/node_modules/path-to-regexp/package.json old mode 100755 new mode 100644 index bccfe25f..648792b7 --- a/server/node_modules/express/node_modules/path-to-regexp/package.json +++ b/server/node_modules/express/node_modules/path-to-regexp/package.json @@ -22,141 +22,15 @@ "mocha": "^1.17.1", "istanbul": "^0.2.6" }, + "readme": "\n# Path-to-RegExp\n\n Turn an Express-style path string such as `/user/:name` into a regular expression.\n\n## Usage\n\n```javascript\nvar pathToRegexp = require('path-to-regexp');\n```\n### pathToRegexp(path, keys, options)\n\n - **path** A string in the express format, an array of such strings, or a regular expression\n - **keys** An array to be populated with the keys present in the url. Once the function completes, this will be an array of strings.\n - **options**\n - **options.sensitive** Defaults to false, set this to true to make routes case sensitive\n - **options.strict** Defaults to false, set this to true to make the trailing slash matter.\n - **options.end** Defaults to true, set this to false to only match the prefix of the URL.\n\n```javascript\nvar keys = [];\nvar exp = pathToRegexp('/foo/:bar', keys);\n//keys = ['bar']\n//exp = /^\\/foo\\/(?:([^\\/]+?))\\/?$/i\n```\n\n## Live Demo\n\nYou can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.com/express-route-tester/).\n\n## License\n\n MIT", + "readmeFilename": "Readme.md", "bugs": { "url": "https://github.com/component/path-to-regexp/issues" }, - "homepage": "https://github.com/component/path-to-regexp", "_id": "path-to-regexp@0.1.3", - "_shasum": "21b9ab82274279de25b156ea08fd12ca51b8aecb", - "_from": "path-to-regexp@0.1.3", - "_npmVersion": "1.4.9", - "_npmUser": { - "name": "blakeembrey", - "email": "hello@blakeembrey.com" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "dominicbarnes", - "email": "dominic@dbarnes.info" - }, - { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - }, - { - "name": "rauchg", - "email": "rauchg@gmail.com" - }, - { - "name": "retrofox", - "email": "rdsuarez@gmail.com" - }, - { - "name": "coreh", - "email": "thecoreh@gmail.com" - }, - { - "name": "forbeslindesay", - "email": "forbes@lindesay.co.uk" - }, - { - "name": "kelonye", - "email": "kelonyemitchel@gmail.com" - }, - { - "name": "mattmueller", - "email": "mattmuelle@gmail.com" - }, - { - "name": "yields", - "email": "yields@icloud.com" - }, - { - "name": "anthonyshort", - "email": "antshort@gmail.com" - }, - { - "name": "ianstormtaylor", - "email": "ian@ianstormtaylor.com" - }, - { - "name": "cristiandouce", - "email": "cristian@gravityonmars.com" - }, - { - "name": "swatinem", - "email": "arpad.borsos@googlemail.com" - }, - { - "name": "stagas", - "email": "gstagas@gmail.com" - }, - { - "name": "amasad", - "email": "amjad.masad@gmail.com" - }, - { - "name": "juliangruber", - "email": "julian@juliangruber.com" - }, - { - "name": "shtylman", - "email": "shtylman@gmail.com" - }, - { - "name": "calvinfo", - "email": "calvin@calv.info" - }, - { - "name": "blakeembrey", - "email": "hello@blakeembrey.com" - }, - { - "name": "timoxley", - "email": "secoif@gmail.com" - }, - { - "name": "jonathanong", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "queckezz", - "email": "fabian.eichenberger@gmail.com" - }, - { - "name": "nami-doc", - "email": "vendethiel@hotmail.fr" - }, - { - "name": "clintwood", - "email": "clint@anotherway.co.za" - }, - { - "name": "thehydroimpulse", - "email": "dnfagnan@gmail.com" - }, - { - "name": "stephenmathieson", - "email": "me@stephenmathieson.com" - }, - { - "name": "trevorgerhardt", - "email": "trevorgerhardt@gmail.com" - } - ], "dist": { - "shasum": "21b9ab82274279de25b156ea08fd12ca51b8aecb", - "tarball": "http://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.3.tgz" + "shasum": "3e1f89ecfacad26e328a72153487050b5c6c59bb" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.3.tgz", - "readme": "ERROR: No README data found!" + "_from": "path-to-regexp@0.1.3", + "_resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.3.tgz" } diff --git a/server/node_modules/express/node_modules/path-to-regexp/test.js b/server/node_modules/express/node_modules/path-to-regexp/test.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/proxy-addr/HISTORY.md b/server/node_modules/express/node_modules/proxy-addr/HISTORY.md old mode 100755 new mode 100644 index 0a695fd0..7248dbb1 --- a/server/node_modules/express/node_modules/proxy-addr/HISTORY.md +++ b/server/node_modules/express/node_modules/proxy-addr/HISTORY.md @@ -1,3 +1,8 @@ +1.0.8 / 2015-05-10 +================== + + * deps: ipaddr.js@1.0.1 + 1.0.7 / 2015-03-16 ================== diff --git a/server/node_modules/express/node_modules/proxy-addr/LICENSE b/server/node_modules/express/node_modules/proxy-addr/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/proxy-addr/README.md b/server/node_modules/express/node_modules/proxy-addr/README.md old mode 100755 new mode 100644 index 57ec4cdb..26f7fc01 --- a/server/node_modules/express/node_modules/proxy-addr/README.md +++ b/server/node_modules/express/node_modules/proxy-addr/README.md @@ -125,13 +125,13 @@ $ npm run-script bench [MIT](LICENSE) -[npm-image]: https://img.shields.io/npm/v/proxy-addr.svg?style=flat +[npm-image]: https://img.shields.io/npm/v/proxy-addr.svg [npm-url]: https://npmjs.org/package/proxy-addr -[node-version-image]: https://img.shields.io/node/v/proxy-addr.svg?style=flat +[node-version-image]: https://img.shields.io/node/v/proxy-addr.svg [node-version-url]: http://nodejs.org/download/ -[travis-image]: https://img.shields.io/travis/jshttp/proxy-addr.svg?style=flat +[travis-image]: https://img.shields.io/travis/jshttp/proxy-addr/master.svg [travis-url]: https://travis-ci.org/jshttp/proxy-addr -[coveralls-image]: https://img.shields.io/coveralls/jshttp/proxy-addr.svg?style=flat +[coveralls-image]: https://img.shields.io/coveralls/jshttp/proxy-addr/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/proxy-addr?branch=master -[downloads-image]: https://img.shields.io/npm/dm/proxy-addr.svg?style=flat +[downloads-image]: https://img.shields.io/npm/dm/proxy-addr.svg [downloads-url]: https://npmjs.org/package/proxy-addr diff --git a/server/node_modules/express/node_modules/proxy-addr/index.js b/server/node_modules/express/node_modules/proxy-addr/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md b/server/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE b/server/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md b/server/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js b/server/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json b/server/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json old mode 100755 new mode 100644 index 7cc4ed6b..4c7cc191 --- a/server/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json +++ b/server/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json @@ -16,7 +16,7 @@ ], "repository": { "type": "git", - "url": "https://github.com/jshttp/forwarded" + "url": "git://github.com/jshttp/forwarded" }, "devDependencies": { "istanbul": "0.3.2", @@ -36,29 +36,11 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" }, - "gitHead": "e9a9faeb3cfaadf40eb57d144fff26bca9b818e8", + "readme": "# forwarded\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nParse HTTP X-Forwarded-For header\n\n## Installation\n\n```sh\n$ npm install forwarded\n```\n\n## API\n\n```js\nvar forwarded = require('forwarded')\n```\n\n### forwarded(req)\n\n```js\nvar addresses = forwarded(req)\n```\n\nParse the `X-Forwarded-For` header from the request. Returns an array\nof the addresses, including the socket address for the `req`. In reverse\norder (i.e. index `0` is the socket address and the last index is the\nfurthest address, typically the end-user).\n\n## Testing\n\n```sh\n$ npm test\n```\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/forwarded.svg?style=flat\n[npm-url]: https://npmjs.org/package/forwarded\n[node-version-image]: https://img.shields.io/node/v/forwarded.svg?style=flat\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/forwarded.svg?style=flat\n[travis-url]: https://travis-ci.org/jshttp/forwarded\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded.svg?style=flat\n[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg?style=flat\n[downloads-url]: https://npmjs.org/package/forwarded\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/forwarded/issues" }, - "homepage": "https://github.com/jshttp/forwarded", "_id": "forwarded@0.1.0", - "_shasum": "19ef9874c4ae1c297bcf078fde63a09b66a84363", - "_from": "forwarded@~0.1.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], - "dist": { - "shasum": "19ef9874c4ae1c297bcf078fde63a09b66a84363", - "tarball": "http://registry.npmjs.org/forwarded/-/forwarded-0.1.0.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.0.tgz" + "_from": "forwarded@~0.1.0" } diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md old mode 100755 new mode 100644 index a8166729..c596e7e3 --- a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md +++ b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md @@ -75,6 +75,18 @@ var range = ipaddr.parse("2001:db8::"); addr.match(range, 32); // => true ``` +Alternatively, `match` can also be called as `match([range, bits])`. In this way, +it can be used together with the `parseCIDR(string)` method, which parses an IP +address together with a CIDR range. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); + +addr.match(ipaddr.parseCIDR("2001:db8::/32")); // => true +``` + A `range()` method returns one of predefined names for several special ranges defined by IP protocols. The exact names (and their respective CIDR ranges) can be looked up in the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `"unicast"` diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js old mode 100755 new mode 100644 index 59634ff7..9e2800de --- a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js +++ b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js @@ -1 +1 @@ -(function(){var t,r,n,e,i,o,a,s;r={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=r:s.ipaddr=r,a=function(t,r,n,e){var i,o;if(t.length!==r.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;e>0;){if(o=n-e,0>o&&(o=0),t[i]>>o!==r[i]>>o)return!1;e-=n,i+=1}return!0},r.subnetMatch=function(t,r,n){var e,i,o,a,s;null==n&&(n="unicast");for(e in r)for(i=r[e],"[object Array]"!==toString.call(i[0])&&(i=[i]),a=0,s=i.length;s>a;a++)if(o=i[a],t.match.apply(t,o))return e;return n},r.IPv4=function(){function t(t){var r,n,e;if(4!==t.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(n=0,e=t.length;e>n;n++)if(r=t[n],!(r>=0&&255>=r))throw new Error("ipaddr: ipv4 octet is a byte");this.octets=t}return t.prototype.kind=function(){return"ipv4"},t.prototype.toString=function(){return this.octets.join(".")},t.prototype.toByteArray=function(){return this.octets.slice(0)},t.prototype.match=function(t,r){if("ipv4"!==t.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return a(this.octets,t.octets,8,r)},t.prototype.SpecialRanges={unspecified:[[new t([0,0,0,0]),8]],broadcast:[[new t([255,255,255,255]),32]],multicast:[[new t([224,0,0,0]),4]],linkLocal:[[new t([169,254,0,0]),16]],loopback:[[new t([127,0,0,0]),8]],"private":[[new t([10,0,0,0]),8],[new t([172,16,0,0]),12],[new t([192,168,0,0]),16]],reserved:[[new t([192,0,0,0]),24],[new t([192,0,2,0]),24],[new t([192,88,99,0]),24],[new t([198,51,100,0]),24],[new t([203,0,113,0]),24],[new t([240,0,0,0]),4]]},t.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},t.prototype.toIPv4MappedAddress=function(){return r.IPv6.parse("::ffff:"+this.toString())},t}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},r.IPv4.parser=function(t){var r,n,i,o,a;if(n=function(t){return"0"===t[0]&&"x"!==t[1]?parseInt(t,8):parseInt(t)},r=t.match(e.fourOctet))return function(){var t,e,o,a;for(o=r.slice(1,6),a=[],t=0,e=o.length;e>t;t++)i=o[t],a.push(n(i));return a}();if(r=t.match(e.longValue)){if(a=n(r[1]),a>4294967295||0>a)throw new Error("ipaddr: address outside defined range");return function(){var t,r;for(r=[],o=t=0;24>=t;o=t+=8)r.push(a>>o&255);return r}().reverse()}return null},r.IPv6=function(){function t(t){var r,n,e;if(8!==t.length)throw new Error("ipaddr: ipv6 part count should be 8");for(n=0,e=t.length;e>n;n++)if(r=t[n],!(r>=0&&65535>=r))throw new Error("ipaddr: ipv6 part should fit to two octets");this.parts=t}return t.prototype.kind=function(){return"ipv6"},t.prototype.toString=function(){var t,r,n,e,i,o,a;for(i=function(){var t,n,e,i;for(e=this.parts,i=[],t=0,n=e.length;n>t;t++)r=e[t],i.push(r.toString(16));return i}.call(this),t=[],n=function(r){return t.push(r)},e=0,o=0,a=i.length;a>o;o++)switch(r=i[o],e){case 0:n("0"===r?"":r),e=1;break;case 1:"0"===r?e=2:n(r);break;case 2:"0"!==r&&(n(""),n(r),e=3);break;case 3:n(r)}return 2===e&&(n(""),n("")),t.join(":")},t.prototype.toByteArray=function(){var t,r,n,e,i;for(t=[],i=this.parts,n=0,e=i.length;e>n;n++)r=i[n],t.push(r>>8),t.push(255&r);return t},t.prototype.toNormalizedString=function(){var t;return function(){var r,n,e,i;for(e=this.parts,i=[],r=0,n=e.length;n>r;r++)t=e[r],i.push(t.toString(16));return i}.call(this).join(":")},t.prototype.match=function(t,r){if("ipv6"!==t.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return a(this.parts,t.parts,16,r)},t.prototype.SpecialRanges={unspecified:[new t([0,0,0,0,0,0,0,0]),128],linkLocal:[new t([65152,0,0,0,0,0,0,0]),10],multicast:[new t([65280,0,0,0,0,0,0,0]),8],loopback:[new t([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new t([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new t([0,0,0,0,0,65535,0,0]),96],rfc6145:[new t([0,0,0,0,65535,0,0,0]),96],rfc6052:[new t([100,65435,0,0,0,0,0,0]),96],"6to4":[new t([8194,0,0,0,0,0,0,0]),16],teredo:[new t([8193,0,0,0,0,0,0,0]),32],reserved:[[new t([8193,3512,0,0,0,0,0,0]),32]]},t.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},t.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},t.prototype.toIPv4Address=function(){var t,n,e;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=this.parts.slice(-2),t=e[0],n=e[1],new r.IPv4([t>>8,255&t,n>>8,255&n])},t}(),i="(?:[0-9a-f]+::?)+",o={"native":new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+(""+n+"\\."+n+"\\."+n+"\\."+n+"$"),"i")},t=function(t,r){var n,e,i,o,a;if(t.indexOf("::")!==t.lastIndexOf("::"))return null;for(n=0,e=-1;(e=t.indexOf(":",e+1))>=0;)n++;if(":"===t[0]&&n--,":"===t[t.length-1]&&n--,n>r)return null;for(a=r-n,o=":";a--;)o+="0:";return t=t.replace("::",o),":"===t[0]&&(t=t.slice(1)),":"===t[t.length-1]&&(t=t.slice(0,-1)),function(){var r,n,e,o;for(e=t.split(":"),o=[],r=0,n=e.length;n>r;r++)i=e[r],o.push(parseInt(i,16));return o}()},r.IPv6.parser=function(r){var n,e;return r.match(o["native"])?t(r,8):(n=r.match(o.transitional))&&(e=t(n[1].slice(0,-1),6))?(e.push(parseInt(n[2])<<8|parseInt(n[3])),e.push(parseInt(n[4])<<8|parseInt(n[5])),e):null},r.IPv4.isIPv4=r.IPv6.isIPv6=function(t){return null!==this.parser(t)},r.IPv4.isValid=r.IPv6.isValid=function(t){var r;try{return new this(this.parser(t)),!0}catch(n){return r=n,!1}},r.IPv4.parse=r.IPv6.parse=function(t){var r;if(r=this.parser(t),null===r)throw new Error("ipaddr: string is not formatted like ip address");return new this(r)},r.isValid=function(t){return r.IPv6.isValid(t)||r.IPv4.isValid(t)},r.parse=function(t){if(r.IPv6.isValid(t))return r.IPv6.parse(t);if(r.IPv4.isValid(t))return r.IPv4.parse(t);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},r.process=function(t){var r;return r=this.parse(t),"ipv6"===r.kind()&&r.isIPv4MappedAddress()?r.toIPv4Address():r}}).call(this); \ No newline at end of file +(function(){var r,t,e,n,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,e,n){var i,o;if(r.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;n>0;){if(o=e-n,0>o&&(o=0),r[i]>>o!==t[i]>>o)return!1;n-=e,i+=1}return!0},t.subnetMatch=function(r,t,e){var n,i,o,a,s;null==e&&(e="unicast");for(n in t)for(i=t[n],"[object Array]"!==toString.call(i[0])&&(i=[i]),a=0,s=i.length;s>a;a++)if(o=i[a],r.match.apply(r,o))return n;return e},t.IPv4=function(){function r(r){var t,e,n;if(4!==r.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(e=0,n=r.length;n>e;e++)if(t=r[e],!(t>=0&&255>=t))throw new Error("ipaddr: ipv4 octet is a byte");this.octets=r}return r.prototype.kind=function(){return"ipv4"},r.prototype.toString=function(){return this.octets.join(".")},r.prototype.toByteArray=function(){return this.octets.slice(0)},r.prototype.match=function(r,t){var e;if(void 0===t&&(e=r,r=e[0],t=e[1]),"ipv4"!==r.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return a(this.octets,r.octets,8,t)},r.prototype.SpecialRanges={unspecified:[[new r([0,0,0,0]),8]],broadcast:[[new r([255,255,255,255]),32]],multicast:[[new r([224,0,0,0]),4]],linkLocal:[[new r([169,254,0,0]),16]],loopback:[[new r([127,0,0,0]),8]],"private":[[new r([10,0,0,0]),8],[new r([172,16,0,0]),12],[new r([192,168,0,0]),16]],reserved:[[new r([192,0,0,0]),24],[new r([192,0,2,0]),24],[new r([192,88,99,0]),24],[new r([198,51,100,0]),24],[new r([203,0,113,0]),24],[new r([240,0,0,0]),4]]},r.prototype.range=function(){return t.subnetMatch(this,this.SpecialRanges)},r.prototype.toIPv4MappedAddress=function(){return t.IPv6.parse("::ffff:"+this.toString())},r}(),e="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp("^"+e+"\\."+e+"\\."+e+"\\."+e+"$","i"),longValue:new RegExp("^"+e+"$","i")},t.IPv4.parser=function(r){var t,e,i,o,a;if(e=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(n.fourOctet))return function(){var r,n,o,a;for(o=t.slice(1,6),a=[],r=0,n=o.length;n>r;r++)i=o[r],a.push(e(i));return a}();if(t=r.match(n.longValue)){if(a=e(t[1]),a>4294967295||0>a)throw new Error("ipaddr: address outside defined range");return function(){var r,t;for(t=[],o=r=0;24>=r;o=r+=8)t.push(a>>o&255);return t}().reverse()}return null},t.IPv6=function(){function r(r){var t,e,n;if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8");for(e=0,n=r.length;n>e;e++)if(t=r[e],!(t>=0&&65535>=t))throw new Error("ipaddr: ipv6 part should fit to two octets");this.parts=r}return r.prototype.kind=function(){return"ipv6"},r.prototype.toString=function(){var r,t,e,n,i,o,a;for(i=function(){var r,e,n,i;for(n=this.parts,i=[],r=0,e=n.length;e>r;r++)t=n[r],i.push(t.toString(16));return i}.call(this),r=[],e=function(t){return r.push(t)},n=0,o=0,a=i.length;a>o;o++)switch(t=i[o],n){case 0:e("0"===t?"":t),n=1;break;case 1:"0"===t?n=2:e(t);break;case 2:"0"!==t&&(e(""),e(t),n=3);break;case 3:e(t)}return 2===n&&(e(""),e("")),r.join(":")},r.prototype.toByteArray=function(){var r,t,e,n,i;for(r=[],i=this.parts,e=0,n=i.length;n>e;e++)t=i[e],r.push(t>>8),r.push(255&t);return r},r.prototype.toNormalizedString=function(){var r;return function(){var t,e,n,i;for(n=this.parts,i=[],t=0,e=n.length;e>t;t++)r=n[t],i.push(r.toString(16));return i}.call(this).join(":")},r.prototype.match=function(r,t){var e;if(void 0===t&&(e=r,r=e[0],t=e[1]),"ipv6"!==r.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return a(this.parts,r.parts,16,t)},r.prototype.SpecialRanges={unspecified:[new r([0,0,0,0,0,0,0,0]),128],linkLocal:[new r([65152,0,0,0,0,0,0,0]),10],multicast:[new r([65280,0,0,0,0,0,0,0]),8],loopback:[new r([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new r([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new r([0,0,0,0,0,65535,0,0]),96],rfc6145:[new r([0,0,0,0,65535,0,0,0]),96],rfc6052:[new r([100,65435,0,0,0,0,0,0]),96],"6to4":[new r([8194,0,0,0,0,0,0,0]),16],teredo:[new r([8193,0,0,0,0,0,0,0]),32],reserved:[[new r([8193,3512,0,0,0,0,0,0]),32]]},r.prototype.range=function(){return t.subnetMatch(this,this.SpecialRanges)},r.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},r.prototype.toIPv4Address=function(){var r,e,n;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return n=this.parts.slice(-2),r=n[0],e=n[1],new t.IPv4([r>>8,255&r,e>>8,255&e])},r}(),i="(?:[0-9a-f]+::?)+",o={"native":new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+(""+e+"\\."+e+"\\."+e+"\\."+e+"$"),"i")},r=function(r,t){var e,n,i,o,a;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for(e=0,n=-1;(n=r.indexOf(":",n+1))>=0;)e++;if(":"===r[0]&&e--,":"===r[r.length-1]&&e--,e>t)return null;for(a=t-e,o=":";a--;)o+="0:";return r=r.replace("::",o),":"===r[0]&&(r=r.slice(1)),":"===r[r.length-1]&&(r=r.slice(0,-1)),function(){var t,e,n,o;for(n=r.split(":"),o=[],t=0,e=n.length;e>t;t++)i=n[t],o.push(parseInt(i,16));return o}()},t.IPv6.parser=function(t){var e,n;return t.match(o["native"])?r(t,8):(e=t.match(o.transitional))&&(n=r(e[1].slice(0,-1),6))?(n.push(parseInt(e[2])<<8|parseInt(e[3])),n.push(parseInt(e[4])<<8|parseInt(e[5])),n):null},t.IPv4.isIPv4=t.IPv6.isIPv6=function(r){return null!==this.parser(r)},t.IPv4.isValid=t.IPv6.isValid=function(r){var t;try{return new this(this.parser(r)),!0}catch(e){return t=e,!1}},t.IPv4.parse=t.IPv6.parse=function(r){var t;if(t=this.parser(r),null===t)throw new Error("ipaddr: string is not formatted like ip address");return new this(t)},t.IPv4.parseCIDR=t.IPv6.parseCIDR=function(r){var t;if(t=r.match(/^(.+)\/(\d+)$/))return[this.parse(t[1]),parseInt(t[2])];throw new Error("ipaddr: string is not formatted like a CIDR range")},t.isValid=function(r){return t.IPv6.isValid(r)||t.IPv4.isValid(r)},t.parse=function(r){if(t.IPv6.isValid(r))return t.IPv6.parse(r);if(t.IPv4.isValid(r))return t.IPv4.parse(r);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},t.parseCIDR=function(r){var e;try{return t.IPv6.parseCIDR(r)}catch(n){e=n;try{return t.IPv4.parseCIDR(r)}catch(n){throw e=n,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},t.process=function(r){var t;return t=this.parse(r),"ipv6"===t.kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(this); \ No newline at end of file diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js old mode 100755 new mode 100644 index 00620a8e..5d99e084 --- a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js +++ b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js @@ -79,6 +79,10 @@ }; IPv4.prototype.match = function(other, cidrRange) { + var _ref; + if (cidrRange === void 0) { + _ref = other, other = _ref[0], cidrRange = _ref[1]; + } if (other.kind() !== 'ipv4') { throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); } @@ -251,6 +255,10 @@ }; IPv6.prototype.match = function(other, cidrRange) { + var _ref; + if (cidrRange === void 0) { + _ref = other, other = _ref[0], cidrRange = _ref[1]; + } if (other.kind() !== 'ipv6') { throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); } @@ -381,6 +389,14 @@ return new this(parts); }; + ipaddr.IPv4.parseCIDR = ipaddr.IPv6.parseCIDR = function(string) { + var match; + if (match = string.match(/^(.+)\/(\d+)$/)) { + return [this.parse(match[1]), parseInt(match[2])]; + } + throw new Error("ipaddr: string is not formatted like a CIDR range"); + }; + ipaddr.isValid = function(string) { return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); }; @@ -395,6 +411,21 @@ } }; + ipaddr.parseCIDR = function(string) { + var e; + try { + return ipaddr.IPv6.parseCIDR(string); + } catch (_error) { + e = _error; + try { + return ipaddr.IPv4.parseCIDR(string); + } catch (_error) { + e = _error; + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + } + } + }; + ipaddr.process = function(string) { var addr; addr = this.parse(string); diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json old mode 100755 new mode 100644 index 99791170..0f00aef0 --- a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json +++ b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json @@ -1,7 +1,7 @@ { "name": "ipaddr.js", "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", - "version": "0.1.9", + "version": "1.0.1", "author": { "name": "Peter Zotov", "email": "whitequark@whitequark.org" @@ -32,27 +32,11 @@ "node": ">= 0.2.5" }, "license": "MIT", - "gitHead": "d51df7aa41ef1875215ae4ffbd324c486f8c2799", + "readme": "# ipaddr.js — an IPv6 and IPv4 address manipulation library\n\nipaddr.js is a small (1.9K minified and gzipped) library for manipulating\nIP addresses in JavaScript environments. It runs on both CommonJS runtimes\n(e.g. [nodejs]) and in a web browser.\n\nipaddr.js allows you to verify and parse string representation of an IP\naddress, match it against a CIDR range or range list, determine if it falls\ninto some reserved ranges (examples include loopback and private ranges),\nand convert between IPv4 and IPv4-mapped IPv6 addresses.\n\n[nodejs]: http://nodejs.org\n\n## Installation\n\n`npm install ipaddr.js`\n\n## API\n\nipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS,\nit is exported from the module:\n\n```js\nvar ipaddr = require('ipaddr.js');\n```\n\nThe API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4.\n\n### Global methods\n\nThere are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and\n`ipaddr.process`. All of them receive a string as a single parameter.\n\nThe `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or\nIPv6 address, and `false` otherwise. It does not throw any exceptions.\n\nThe `ipaddr.parse` method returns an object representing the IP address,\nor throws an `Error` if the passed string is not a valid representation of an\nIP address.\n\nThe `ipaddr.process` method works just like the `ipaddr.parse` one, but it\nautomatically converts IPv4-mapped IPv6 addresses to their IPv4 couterparts\nbefore returning. It is useful when you have a Node.js instance listening\non an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its\nequivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4\nconnections on your IPv6-only socket, but the remote address will be mangled.\nUse `ipaddr.process` method to automatically demangle it.\n\n### Object representation\n\nParsing methods return an object which descends from `ipaddr.IPv6` or\n`ipaddr.IPv4`. These objects share some properties, but most of them differ.\n\n#### Shared properties\n\nOne can determine the type of address by calling `addr.kind()`. It will return\neither `\"ipv6\"` or `\"ipv4\"`.\n\nAn address can be converted back to its string representation with `addr.toString()`.\nNote that this method:\n * does not return the original string used to create the object (in fact, there is\n no way of getting that string)\n * returns a compact representation (when it is applicable)\n\nA `match(range, bits)` method can be used to check if the address falls into a\ncertain CIDR range.\nNote that an address can be (obviously) matched only against an address of the same type.\n\nFor example:\n\n```js\nvar addr = ipaddr.parse(\"2001:db8:1234::1\");\nvar range = ipaddr.parse(\"2001:db8::\");\n\naddr.match(range, 32); // => true\n```\n\nAlternatively, `match` can also be called as `match([range, bits])`. In this way,\nit can be used together with the `parseCIDR(string)` method, which parses an IP\naddress together with a CIDR range.\n\nFor example:\n\n```js\nvar addr = ipaddr.parse(\"2001:db8:1234::1\");\n\naddr.match(ipaddr.parseCIDR(\"2001:db8::/32\")); // => true\n```\n\nA `range()` method returns one of predefined names for several special ranges defined\nby IP protocols. The exact names (and their respective CIDR ranges) can be looked up\nin the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `\"unicast\"`\n(the default one) and `\"reserved\"`.\n\nYou can match against your own range list by using\n`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with both\nIPv6 and IPv4 addresses, and accepts a name-to-subnet map as the range list. For example:\n\n```js\nvar rangeList = {\n documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ],\n tunnelProviders: [\n [ ipaddr.parse('2001:470::'), 32 ], // he.net\n [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6\n ]\n};\nipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => \"he.net\"\n```\n\nThe addresses can be converted to their byte representation with `toByteArray()`.\n(Actually, JavaScript mostly does not know about byte buffers. They are emulated with\narrays of numbers, each in range of 0..255.)\n\n```js\nvar bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com\nbytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ]\n```\n\nThe `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them\nhave the same interface for both protocols, and are similar to global methods.\n\n`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address\nfor particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser.\n\n[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186\n[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71\n\n#### IPv6 properties\n\nSometimes you will want to convert IPv6 not to a compact string representation (with\nthe `::` substitution); the `toNormalizedString()` method will return an address where\nall zeroes are explicit.\n\nFor example:\n\n```js\nvar addr = ipaddr.parse(\"2001:0db8::0001\");\naddr.toString(); // => \"2001:db8::1\"\naddr.toNormalizedString(); // => \"2001:db8:0:0:0:0:0:1\"\n```\n\nThe `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped\none, and `toIPv4Address()` will return an IPv4 object address.\n\nTo access the underlying binary representation of the address, use `addr.parts`.\n\n```js\nvar addr = ipaddr.parse(\"2001:db8:10::1234:DEAD\");\naddr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead]\n```\n\n#### IPv4 properties\n\n`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address.\n\nTo access the underlying representation of the address, use `addr.octets`.\n\n```js\nvar addr = ipaddr.parse(\"192.168.1.1\");\naddr.octets // => [192, 168, 1, 1]\n```\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/whitequark/ipaddr.js/issues" }, - "_id": "ipaddr.js@0.1.9", - "_shasum": "a9c78ccc12dc9010f296ab9aef2f61f432d69efa", - "_from": "ipaddr.js@0.1.9", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "whitequark", - "email": "whitequark@whitequark.org" - }, - "maintainers": [ - { - "name": "whitequark", - "email": "whitequark@whitequark.org" - } - ], - "dist": { - "shasum": "a9c78ccc12dc9010f296ab9aef2f61f432d69efa", - "tarball": "http://registry.npmjs.org/ipaddr.js/-/ipaddr.js-0.1.9.tgz" - }, - "_resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-0.1.9.tgz" + "_id": "ipaddr.js@1.0.1", + "_from": "ipaddr.js@1.0.1" } diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee old mode 100755 new mode 100644 index a6d358e3..0a48080f --- a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee +++ b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee @@ -67,6 +67,9 @@ class ipaddr.IPv4 # Checks if this address matches other one within given CIDR range. match: (other, cidrRange) -> + if cidrRange == undefined + [other, cidrRange] = other + if other.kind() != 'ipv4' throw new Error "ipaddr: cannot match ipv4 address with non-ipv4 one" @@ -211,6 +214,9 @@ class ipaddr.IPv6 # Checks if this address matches other one within given CIDR range. match: (other, cidrRange) -> + if cidrRange == undefined + [other, cidrRange] = other + if other.kind() != 'ipv6' throw new Error "ipaddr: cannot match ipv6 address with non-ipv6 one" @@ -331,6 +337,12 @@ ipaddr.IPv4.parse = ipaddr.IPv6.parse = (string) -> return new this(parts) +ipaddr.IPv4.parseCIDR = ipaddr.IPv6.parseCIDR = (string) -> + if match = string.match(/^(.+)\/(\d+)$/) + return [@parse(match[1]), parseInt(match[2])] + + throw new Error "ipaddr: string is not formatted like a CIDR range" + # Checks if the address is valid IP address ipaddr.isValid = (string) -> return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string) @@ -344,6 +356,15 @@ ipaddr.parse = (string) -> else throw new Error "ipaddr: the address has neither IPv6 nor IPv4 format" +ipaddr.parseCIDR = (string) -> + try + return ipaddr.IPv6.parseCIDR(string) + catch e + try + return ipaddr.IPv4.parseCIDR(string) + catch e + throw new Error "ipaddr: the address has neither IPv6 nor IPv4 CIDR format" + # Parse an address and return plain IPv4 address if it is an IPv4-mapped address ipaddr.process = (string) -> addr = @parse(string) diff --git a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee old mode 100755 new mode 100644 index 627503d6..361561e7 --- a/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee +++ b/server/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee @@ -73,6 +73,22 @@ module.exports = test.equal(addr.match(addr, 32), true) test.done() + 'parses IPv4 CIDR correctly': (test) -> + addr = new ipaddr.IPv4([10, 5, 0, 1]) + test.equal(addr.match(ipaddr.IPv4.parseCIDR('0.0.0.0/0')), true) + test.equal(addr.match(ipaddr.IPv4.parseCIDR('11.0.0.0/8')), false) + test.equal(addr.match(ipaddr.IPv4.parseCIDR('10.0.0.0/8')), true) + test.equal(addr.match(ipaddr.IPv4.parseCIDR('10.0.0.1/8')), true) + test.equal(addr.match(ipaddr.IPv4.parseCIDR('10.0.0.10/8')), true) + test.equal(addr.match(ipaddr.IPv4.parseCIDR('10.5.5.0/16')), true) + test.equal(addr.match(ipaddr.IPv4.parseCIDR('10.4.5.0/16')), false) + test.equal(addr.match(ipaddr.IPv4.parseCIDR('10.4.5.0/15')), true) + test.equal(addr.match(ipaddr.IPv4.parseCIDR('10.5.0.2/32')), false) + test.equal(addr.match(ipaddr.IPv4.parseCIDR('10.5.0.1/32')), true) + test.throws -> + ipaddr.IPv4.parseCIDR('10.5.0.1') + test.done() + 'detects reserved IPv4 networks': (test) -> test.equal(ipaddr.IPv4.parse('0.0.0.0').range(), 'unspecified') test.equal(ipaddr.IPv4.parse('0.1.0.0').range(), 'unspecified') @@ -159,6 +175,19 @@ module.exports = test.equal(addr.match(addr, 128), true) test.done() + 'parses IPv6 CIDR correctly': (test) -> + addr = ipaddr.IPv6.parse('2001:db8:f53a::1') + test.equal(addr.match(ipaddr.IPv6.parseCIDR('::/0')), true) + test.equal(addr.match(ipaddr.IPv6.parseCIDR('2001:db8:f53a::1:1/64')), true) + test.equal(addr.match(ipaddr.IPv6.parseCIDR('2001:db8:f53b::1:1/48')), false) + test.equal(addr.match(ipaddr.IPv6.parseCIDR('2001:db8:f531::1:1/44')), true) + test.equal(addr.match(ipaddr.IPv6.parseCIDR('2001:db8:f500::1/40')), true) + test.equal(addr.match(ipaddr.IPv6.parseCIDR('2001:db9:f500::1/40')), false) + test.equal(addr.match(ipaddr.IPv6.parseCIDR('2001:db8:f53a::1/128')), true) + test.throws -> + ipaddr.IPv6.parseCIDR('2001:db8:f53a::1') + test.done() + 'converts between IPv4-mapped IPv6 addresses and IPv4 addresses': (test) -> addr = ipaddr.IPv4.parse('77.88.21.11') mapped = addr.toIPv4MappedAddress() @@ -216,6 +245,13 @@ module.exports = test.deepEqual(new ipaddr.IPv4([0, 0, 0, 1]), ipaddr.parse('1')) test.done() + 'correctly detects IPv4 and IPv6 CIDR addresses': (test) -> + test.deepEqual([ipaddr.IPv6.parse('fc00::'), 64], + ipaddr.parseCIDR('fc00::/64')) + test.deepEqual([ipaddr.IPv4.parse('1.2.3.4'), 5], + ipaddr.parseCIDR('1.2.3.4/5')) + test.done() + 'does not consider a very large or very small number a valid IP address': (test) -> test.equal(ipaddr.isValid('4999999999'), false) test.equal(ipaddr.isValid('-1'), false) diff --git a/server/node_modules/express/node_modules/proxy-addr/package.json b/server/node_modules/express/node_modules/proxy-addr/package.json old mode 100755 new mode 100644 index 4e1f3591..e2ed5952 --- a/server/node_modules/express/node_modules/proxy-addr/package.json +++ b/server/node_modules/express/node_modules/proxy-addr/package.json @@ -1,7 +1,7 @@ { "name": "proxy-addr", "description": "Determine address of proxied request", - "version": "1.0.7", + "version": "1.0.8", "author": { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" @@ -14,16 +14,16 @@ ], "repository": { "type": "git", - "url": "https://github.com/jshttp/proxy-addr" + "url": "git://github.com/jshttp/proxy-addr" }, "dependencies": { "forwarded": "~0.1.0", - "ipaddr.js": "0.1.9" + "ipaddr.js": "1.0.1" }, "devDependencies": { "benchmark": "1.0.0", "beautify-benchmark": "0.2.4", - "istanbul": "0.3.8", + "istanbul": "0.3.9", "mocha": "~1.21.5" }, "files": [ @@ -41,50 +41,11 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" }, - "gitHead": "917fa69ae1a4c3e2962d89461b6945538b763b28", + "readme": "# proxy-addr\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nDetermine address of proxied request\n\n## Install\n\n```sh\n$ npm install proxy-addr\n```\n\n## API\n\n```js\nvar proxyaddr = require('proxy-addr')\n```\n\n### proxyaddr(req, trust)\n\nReturn the address of the request, using the given `trust` parameter.\n\nThe `trust` argument is a function that returns `true` if you trust\nthe address, `false` if you don't. The closest untrusted address is\nreturned.\n\n```js\nproxyaddr(req, function(addr){ return addr === '127.0.0.1' })\nproxyaddr(req, function(addr, i){ return i < 1 })\n```\n\nThe `trust` arugment may also be a single IP address string or an\narray of trusted addresses, as plain IP addresses, CIDR-formatted\nstrings, or IP/netmask strings.\n\n```js\nproxyaddr(req, '127.0.0.1')\nproxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8'])\nproxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0'])\n```\n\nThis module also supports IPv6. Your IPv6 addresses will be normalized\nautomatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`).\n\n```js\nproxyaddr(req, '::1')\nproxyaddr(req, ['::1/128', 'fe80::/10'])\nproxyaddr(req, ['fe80::/ffc0::'])\n```\n\nThis module will automatically work with IPv4-mapped IPv6 addresses\nas well to support node.js in IPv6-only mode. This means that you do\nnot have to specify both `::ffff:a00:1` and `10.0.0.1`.\n\nAs a convenience, this module also takes certain pre-defined names\nin addition to IP addresses, which expand into IP addresses:\n\n```js\nproxyaddr(req, 'loopback')\nproxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64'])\n```\n\n * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and\n `127.0.0.1`).\n * `linklocal`: IPv4 and IPv6 link-local addresses (like\n `fe80::1:1:1:1` and `169.254.0.1`).\n * `uniquelocal`: IPv4 private addresses and IPv6 unique-local\n addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`).\n\nWhen `trust` is specified as a function, it will be called for each\naddress to determine if it is a trusted address. The function is\ngiven two arguments: `addr` and `i`, where `addr` is a string of\nthe address to check and `i` is a number that represents the distance\nfrom the socket address.\n\n### proxyaddr.all(req, [trust])\n\nReturn all the addresses of the request, optionally stopping at the\nfirst untrusted. This array is ordered from closest to furthest\n(i.e. `arr[0] === req.connection.remoteAddress`).\n\n```js\nproxyaddr.all(req)\n```\n\nThe optional `trust` argument takes the same arguments as `trust`\ndoes in `proxyaddr(req, trust)`.\n\n```js\nproxyaddr.all(req, 'loopback')\n```\n\n### proxyaddr.compile(val)\n\nCompiles argument `val` into a `trust` function. This function takes\nthe same arguments as `trust` does in `proxyaddr(req, trust)` and\nreturns a function suitable for `proxyaddr(req, trust)`.\n\n```js\nvar trust = proxyaddr.compile('localhost')\nvar addr = proxyaddr(req, trust)\n```\n\nThis function is meant to be optimized for use against every request.\nIt is recommend to compile a trust function up-front for the trusted\nconfiguration and pass that to `proxyaddr(req, trust)` for each request.\n\n## Testing\n\n```sh\n$ npm test\n```\n\n## Benchmarks\n\n```sh\n$ npm run-script bench\n```\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/proxy-addr.svg\n[npm-url]: https://npmjs.org/package/proxy-addr\n[node-version-image]: https://img.shields.io/node/v/proxy-addr.svg\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/proxy-addr/master.svg\n[travis-url]: https://travis-ci.org/jshttp/proxy-addr\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/proxy-addr/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/proxy-addr?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/proxy-addr.svg\n[downloads-url]: https://npmjs.org/package/proxy-addr\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/proxy-addr/issues" }, - "homepage": "https://github.com/jshttp/proxy-addr", - "_id": "proxy-addr@1.0.7", - "_shasum": "6e2655aa9c56b014f09734a7e6d558cc77751939", - "_from": "proxy-addr@~1.0.3", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "shtylman", - "email": "shtylman@gmail.com" - }, - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "mscdex", - "email": "mscdex@mscdex.net" - }, - { - "name": "fishrock123", - "email": "fishrock123@rocketmail.com" - } - ], - "dist": { - "shasum": "6e2655aa9c56b014f09734a7e6d558cc77751939", - "tarball": "http://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.7.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.7.tgz", - "readme": "ERROR: No README data found!" + "_id": "proxy-addr@1.0.8", + "_from": "proxy-addr@~1.0.8" } diff --git a/server/node_modules/express/node_modules/qs/.jshintignore b/server/node_modules/express/node_modules/qs/.jshintignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/qs/.jshintrc b/server/node_modules/express/node_modules/qs/.jshintrc old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/qs/.npmignore b/server/node_modules/express/node_modules/qs/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/qs/.travis.yml b/server/node_modules/express/node_modules/qs/.travis.yml old mode 100755 new mode 100644 index c891dd0e..f5021788 --- a/server/node_modules/express/node_modules/qs/.travis.yml +++ b/server/node_modules/express/node_modules/qs/.travis.yml @@ -1,4 +1,6 @@ language: node_js node_js: - - 0.10 \ No newline at end of file + - 0.10 + - 0.12 + - iojs diff --git a/server/node_modules/express/node_modules/qs/CHANGELOG.md b/server/node_modules/express/node_modules/qs/CHANGELOG.md old mode 100755 new mode 100644 index a6dd5a57..378370b6 --- a/server/node_modules/express/node_modules/qs/CHANGELOG.md +++ b/server/node_modules/express/node_modules/qs/CHANGELOG.md @@ -1,6 +1,19 @@ +## [**2.4.1**](https://github.com/hapijs/qs/issues?milestone=20&state=closed) +- [**#73**](https://github.com/hapijs/qs/issues/73) Property 'hasOwnProperty' of object # is not a function + +## [**2.4.0**](https://github.com/hapijs/qs/issues?milestone=19&state=closed) +- [**#70**](https://github.com/hapijs/qs/issues/70) Add arrayFormat option + +## [**2.3.3**](https://github.com/hapijs/qs/issues?milestone=18&state=closed) +- [**#59**](https://github.com/hapijs/qs/issues/59) make sure array indexes are >= 0, closes #57 +- [**#58**](https://github.com/hapijs/qs/issues/58) make qs usable for browser loader + +## [**2.3.2**](https://github.com/hapijs/qs/issues?milestone=17&state=closed) +- [**#55**](https://github.com/hapijs/qs/issues/55) allow merging a string into an object + ## [**2.3.1**](https://github.com/hapijs/qs/issues?milestone=16&state=closed) -- [**#52**](https://github.com/hapijs/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError". +- [**#52**](https://github.com/hapijs/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError". ## [**2.3.0**](https://github.com/hapijs/qs/issues?milestone=15&state=closed) - [**#50**](https://github.com/hapijs/qs/issues/50) add option to omit array indices, closes #46 @@ -27,9 +40,9 @@ - [**#31**](https://github.com/hapijs/qs/issues/31) qs.parse stackoverflow on circular objects ## [**2.2.0**](https://github.com/hapijs/qs/issues?milestone=9&state=closed) -- [**#26**](https://github.com/hapijs/qs/issues/26) Don't use Buffer global if it's not present +- [**#26**](https://github.com/hapijs/qs/issues/26) Don't use Buffer global if it's not present - [**#30**](https://github.com/hapijs/qs/issues/30) Bug when merging non-object values into arrays -- [**#29**](https://github.com/hapijs/qs/issues/29) Don't call Utils.clone at the top of Utils.merge +- [**#29**](https://github.com/hapijs/qs/issues/29) Don't call Utils.clone at the top of Utils.merge - [**#23**](https://github.com/hapijs/qs/issues/23) Ability to not limit parameters? ## [**2.1.0**](https://github.com/hapijs/qs/issues?milestone=8&state=closed) @@ -41,7 +54,7 @@ - [**#21**](https://github.com/hapijs/qs/issues/21) make all limits optional, for #18, for #20 ## [**1.2.2**](https://github.com/hapijs/qs/issues?milestone=6&state=closed) -- [**#19**](https://github.com/hapijs/qs/issues/19) Don't overwrite null values +- [**#19**](https://github.com/hapijs/qs/issues/19) Don't overwrite null values ## [**1.2.1**](https://github.com/hapijs/qs/issues?milestone=5&state=closed) - [**#16**](https://github.com/hapijs/qs/issues/16) ignore non-string delimiters @@ -58,4 +71,3 @@ ## [**1.0.2**](https://github.com/hapijs/qs/issues?milestone=2&state=closed) - [**#5**](https://github.com/hapijs/qs/issues/5) array holes incorrectly copied into object on large index - diff --git a/server/node_modules/express/node_modules/qs/CONTRIBUTING.md b/server/node_modules/express/node_modules/qs/CONTRIBUTING.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/qs/Makefile b/server/node_modules/express/node_modules/qs/Makefile old mode 100755 new mode 100644 index 600a700e..31cc899d --- a/server/node_modules/express/node_modules/qs/Makefile +++ b/server/node_modules/express/node_modules/qs/Makefile @@ -1,8 +1,8 @@ test: - @node node_modules/lab/bin/lab + @node node_modules/lab/bin/lab -a code -L test-cov: - @node node_modules/lab/bin/lab -t 100 + @node node_modules/lab/bin/lab -a code -t 100 -L test-cov-html: - @node node_modules/lab/bin/lab -r html -o coverage.html + @node node_modules/lab/bin/lab -a code -L -r html -o coverage.html -.PHONY: test test-cov test-cov-html \ No newline at end of file +.PHONY: test test-cov test-cov-html diff --git a/server/node_modules/express/node_modules/qs/README.md b/server/node_modules/express/node_modules/qs/README.md index 4f4e743b..2d7e7f5a 100755 --- a/server/node_modules/express/node_modules/qs/README.md +++ b/server/node_modules/express/node_modules/qs/README.md @@ -153,6 +153,8 @@ Qs.parse('a[1]=b', { arrayLimit: 0 }); // { a: { '1': 'b' } } ``` +To disable array parsing entirely, set `arrayLimit` to `-1`. + If you mix notations, **qs** will merge the two items into an object: ```javascript @@ -198,6 +200,17 @@ Qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }); // 'a=b&a=c&a=d' ``` +You may use the `arrayFormat` option to specify the format of the output array + +```javascript +Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) +// 'a[0]=b&a[1]=c' +Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) +// 'a[]=b&a[]=c' +Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) +// 'a=b&a=c' +``` + Empty strings and null values will omit the value, but the equals sign (=) remains in place: ```javascript diff --git a/server/node_modules/express/node_modules/qs/index.js b/server/node_modules/express/node_modules/qs/index.js old mode 100755 new mode 100644 index bb0a047c..2291cd85 --- a/server/node_modules/express/node_modules/qs/index.js +++ b/server/node_modules/express/node_modules/qs/index.js @@ -1 +1 @@ -module.exports = require('./lib'); +module.exports = require('./lib/'); diff --git a/server/node_modules/express/node_modules/qs/lib/parse.js b/server/node_modules/express/node_modules/qs/lib/parse.js index 36273978..5c154bb6 100755 --- a/server/node_modules/express/node_modules/qs/lib/parse.js +++ b/server/node_modules/express/node_modules/qs/lib/parse.js @@ -29,7 +29,7 @@ internals.parseValues = function (str, options) { var key = Utils.decode(part.slice(0, pos)); var val = Utils.decode(part.slice(pos + 1)); - if (!obj.hasOwnProperty(key)) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { obj[key] = val; } else { @@ -62,6 +62,7 @@ internals.parseObject = function (chain, val, options) { if (!isNaN(index) && root !== cleanRoot && indexString === cleanRoot && + index >= 0 && index <= options.arrayLimit) { obj = []; diff --git a/server/node_modules/express/node_modules/qs/lib/stringify.js b/server/node_modules/express/node_modules/qs/lib/stringify.js index b4411047..3ce6cc19 100755 --- a/server/node_modules/express/node_modules/qs/lib/stringify.js +++ b/server/node_modules/express/node_modules/qs/lib/stringify.js @@ -7,11 +7,21 @@ var Utils = require('./utils'); var internals = { delimiter: '&', - indices: true + arrayPrefixGenerators: { + brackets: function (prefix, key) { + return prefix + '[]'; + }, + indices: function (prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function (prefix, key) { + return prefix; + } + } }; -internals.stringify = function (obj, prefix, options) { +internals.stringify = function (obj, prefix, generateArrayPrefix) { if (Utils.isBuffer(obj)) { obj = obj.toString(); @@ -39,13 +49,11 @@ internals.stringify = function (obj, prefix, options) { var objKeys = Object.keys(obj); for (var i = 0, il = objKeys.length; i < il; ++i) { var key = objKeys[i]; - if (!options.indices && - Array.isArray(obj)) { - - values = values.concat(internals.stringify(obj[key], prefix, options)); + if (Array.isArray(obj)) { + values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix)); } else { - values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', options)); + values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix)); } } @@ -57,7 +65,6 @@ module.exports = function (obj, options) { options = options || {}; var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter; - options.indices = typeof options.indices === 'boolean' ? options.indices : internals.indices; var keys = []; @@ -67,10 +74,23 @@ module.exports = function (obj, options) { return ''; } + var arrayFormat; + if (options.arrayFormat in internals.arrayPrefixGenerators) { + arrayFormat = options.arrayFormat; + } + else if ('indices' in options) { + arrayFormat = options.indices ? 'indices' : 'repeat'; + } + else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = internals.arrayPrefixGenerators[arrayFormat]; + var objKeys = Object.keys(obj); for (var i = 0, il = objKeys.length; i < il; ++i) { var key = objKeys[i]; - keys = keys.concat(internals.stringify(obj[key], key, options)); + keys = keys.concat(internals.stringify(obj[key], key, generateArrayPrefix)); } return keys.join(delimiter); diff --git a/server/node_modules/express/node_modules/qs/lib/utils.js b/server/node_modules/express/node_modules/qs/lib/utils.js index 3184d071..5240bd5b 100755 --- a/server/node_modules/express/node_modules/qs/lib/utils.js +++ b/server/node_modules/express/node_modules/qs/lib/utils.js @@ -94,7 +94,7 @@ exports.compact = function (obj, refs) { if (Array.isArray(obj)) { var compacted = []; - for (var i = 0, l = obj.length; i < l; ++i) { + for (var i = 0, il = obj.length; i < il; ++i) { if (typeof obj[i] !== 'undefined') { compacted.push(obj[i]); } @@ -104,7 +104,7 @@ exports.compact = function (obj, refs) { } var keys = Object.keys(obj); - for (var i = 0, il = keys.length; i < il; ++i) { + for (i = 0, il = keys.length; i < il; ++i) { var key = keys[i]; obj[key] = exports.compact(obj[key], refs); } diff --git a/server/node_modules/express/node_modules/qs/package.json b/server/node_modules/express/node_modules/qs/package.json old mode 100755 new mode 100644 index 55c1a676..67864dec --- a/server/node_modules/express/node_modules/qs/package.json +++ b/server/node_modules/express/node_modules/qs/package.json @@ -1,12 +1,13 @@ { "name": "qs", - "version": "2.3.2", + "version": "2.4.2", "description": "A querystring parser that supports nesting and arrays, with a depth limit", "homepage": "https://github.com/hapijs/qs", "main": "index.js", "dependencies": {}, "devDependencies": { - "lab": "4.x.x" + "code": "1.x.x", + "lab": "5.x.x" }, "scripts": { "test": "make test-cov" @@ -25,32 +26,15 @@ "url": "http://github.com/hapijs/qs/raw/master/LICENSE" } ], - "gitHead": "58097c12559b4c5857af99927273b3141dff8529", + "readme": "# qs\n\nA querystring parsing and stringifying library with some added security.\n\n[![Build Status](https://secure.travis-ci.org/hapijs/qs.svg)](http://travis-ci.org/hapijs/qs)\n\nLead Maintainer: [Nathan LaFreniere](https://github.com/nlf)\n\nThe **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring).\n\n## Usage\n\n```javascript\nvar Qs = require('qs');\n\nvar obj = Qs.parse('a=c'); // { a: 'c' }\nvar str = Qs.stringify(obj); // 'a=c'\n```\n\n### Parsing Objects\n\n```javascript\nQs.parse(string, [options]);\n```\n\n**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`.\nFor example, the string `'foo[bar]=baz'` converts to:\n\n```javascript\n{\n foo: {\n bar: 'baz'\n }\n}\n```\n\nURI encoded strings work too:\n\n```javascript\nQs.parse('a%5Bb%5D=c');\n// { a: { b: 'c' } }\n```\n\nYou can also nest your objects, like `'foo[bar][baz]=foobarbaz'`:\n\n```javascript\n{\n foo: {\n bar: {\n baz: 'foobarbaz'\n }\n }\n}\n```\n\nBy default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like\n`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be:\n\n```javascript\n{\n a: {\n b: {\n c: {\n d: {\n e: {\n f: {\n '[g][h][i]': 'j'\n }\n }\n }\n }\n }\n }\n}\n```\n\nThis depth can be overridden by passing a `depth` option to `Qs.parse(string, [options])`:\n\n```javascript\nQs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 });\n// { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }\n```\n\nThe depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number.\n\nFor similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option:\n\n```javascript\nQs.parse('a=b&c=d', { parameterLimit: 1 });\n// { a: 'b' }\n```\n\nAn optional delimiter can also be passed:\n\n```javascript\nQs.parse('a=b;c=d', { delimiter: ';' });\n// { a: 'b', c: 'd' }\n```\n\nDelimiters can be a regular expression too:\n\n```javascript\nQs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ });\n// { a: 'b', c: 'd', e: 'f' }\n```\n\n### Parsing Arrays\n\n**qs** can also parse arrays using a similar `[]` notation:\n\n```javascript\nQs.parse('a[]=b&a[]=c');\n// { a: ['b', 'c'] }\n```\n\nYou may specify an index as well:\n\n```javascript\nQs.parse('a[1]=c&a[0]=b');\n// { a: ['b', 'c'] }\n```\n\nNote that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number\nto create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving\ntheir order:\n\n```javascript\nQs.parse('a[1]=b&a[15]=c');\n// { a: ['b', 'c'] }\n```\n\nNote that an empty string is also a value, and will be preserved:\n\n```javascript\nQs.parse('a[]=&a[]=b');\n// { a: ['', 'b'] }\nQs.parse('a[0]=b&a[1]=&a[2]=c');\n// { a: ['b', '', 'c'] }\n```\n\n**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will\ninstead be converted to an object with the index as the key:\n\n```javascript\nQs.parse('a[100]=b');\n// { a: { '100': 'b' } }\n```\n\nThis limit can be overridden by passing an `arrayLimit` option:\n\n```javascript\nQs.parse('a[1]=b', { arrayLimit: 0 });\n// { a: { '1': 'b' } }\n```\n\nTo disable array parsing entirely, set `arrayLimit` to `-1`.\n\nIf you mix notations, **qs** will merge the two items into an object:\n\n```javascript\nQs.parse('a[0]=b&a[b]=c');\n// { a: { '0': 'b', b: 'c' } }\n```\n\nYou can also create arrays of objects:\n\n```javascript\nQs.parse('a[][b]=c');\n// { a: [{ b: 'c' }] }\n```\n\n### Stringifying\n\n```javascript\nQs.stringify(object, [options]);\n```\n\nWhen stringifying, **qs** always URI encodes output. Objects are stringified as you would expect:\n\n```javascript\nQs.stringify({ a: 'b' });\n// 'a=b'\nQs.stringify({ a: { b: 'c' } });\n// 'a%5Bb%5D=c'\n```\n\nExamples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage.\n\nWhen arrays are stringified, by default they are given explicit indices:\n\n```javascript\nQs.stringify({ a: ['b', 'c', 'd'] });\n// 'a[0]=b&a[1]=c&a[2]=d'\n```\n\nYou may override this by setting the `indices` option to `false`:\n\n```javascript\nQs.stringify({ a: ['b', 'c', 'd'] }, { indices: false });\n// 'a=b&a=c&a=d'\n```\n\nYou may use the `arrayFormat` option to specify the format of the output array\n\n```javascript\nQs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })\n// 'a[0]=b&a[1]=c'\nQs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })\n// 'a[]=b&a[]=c'\nQs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })\n// 'a=b&a=c'\n```\n\nEmpty strings and null values will omit the value, but the equals sign (=) remains in place:\n\n```javascript\nQs.stringify({ a: '' });\n// 'a='\n```\n\nProperties that are set to `undefined` will be omitted entirely:\n\n```javascript\nQs.stringify({ a: null, b: undefined });\n// 'a='\n```\n\nThe delimiter may be overridden with stringify as well:\n\n```javascript\nQs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' });\n// 'a=b;c=d'\n```\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/hapijs/qs/issues" }, - "_id": "qs@2.3.2", - "_shasum": "d45ec249e4b9b029af008829a101d5ff7e972790", - "_from": "qs@2.3.2", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "nlf", - "email": "quitlahok@gmail.com" - }, - "maintainers": [ - { - "name": "nlf", - "email": "quitlahok@gmail.com" - }, - { - "name": "hueniverse", - "email": "eran@hueniverse.com" - } - ], + "_id": "qs@2.4.2", "dist": { - "shasum": "d45ec249e4b9b029af008829a101d5ff7e972790", - "tarball": "http://registry.npmjs.org/qs/-/qs-2.3.2.tgz" + "shasum": "7fe736c898e1b2696e5f8a96e119d5d28f9d1c72" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/qs/-/qs-2.3.2.tgz" + "_from": "qs@2.4.2", + "_resolved": "https://registry.npmjs.org/qs/-/qs-2.4.2.tgz" } diff --git a/server/node_modules/express/node_modules/qs/test/parse.js b/server/node_modules/express/node_modules/qs/test/parse.js index 2a3d1696..79c575b8 100755 --- a/server/node_modules/express/node_modules/qs/test/parse.js +++ b/server/node_modules/express/node_modules/qs/test/parse.js @@ -1,5 +1,7 @@ +/* eslint no-extend-native:0 */ // Load modules +var Code = require('code'); var Lab = require('lab'); var Qs = require('../'); @@ -12,7 +14,7 @@ var internals = {}; // Test shortcuts var lab = exports.lab = Lab.script(); -var expect = Lab.expect; +var expect = Code.expect; var describe = lab.experiment; var it = lab.test; @@ -185,10 +187,11 @@ describe('parse()', function () { it('cannot override prototypes', function (done) { - var obj = Qs.parse('toString=bad&bad[toString]=bad&constructor=bad'); + var obj = Qs.parse('hasOwnProperty=bad&toString=bad&bad[toString]=bad&constructor=bad'); expect(typeof obj.toString).to.equal('function'); expect(typeof obj.bad.toString).to.equal('function'); expect(typeof obj.constructor).to.equal('function'); + expect(typeof obj.hasOwnProperty).to.equal('function'); done(); }); @@ -302,6 +305,8 @@ describe('parse()', function () { it('allows overriding array limit', function (done) { + expect(Qs.parse('a[0]=b', { arrayLimit: -1 })).to.deep.equal({ a: { '0': 'b' } }); + expect(Qs.parse('a[-1]=b', { arrayLimit: -1 })).to.deep.equal({ a: { '-1': 'b' } }); expect(Qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 })).to.deep.equal({ a: { '0': 'b', '1': 'c' } }); done(); }); @@ -309,14 +314,14 @@ describe('parse()', function () { it('parses an object', function (done) { var input = { - "user[name]": {"pop[bob]": 3}, - "user[email]": null + 'user[name]': {'pop[bob]': 3}, + 'user[email]': null }; var expected = { - "user": { - "name": {"pop[bob]": 3}, - "email": null + 'user': { + 'name': {'pop[bob]': 3}, + 'email': null } }; @@ -329,14 +334,14 @@ describe('parse()', function () { it('parses an object and not child values', function (done) { var input = { - "user[name]": {"pop[bob]": { "test": 3 }}, - "user[email]": null + 'user[name]': {'pop[bob]': { 'test': 3 }}, + 'user[email]': null }; var expected = { - "user": { - "name": {"pop[bob]": { "test": 3 }}, - "email": null + 'user': { + 'name': {'pop[bob]': { 'test': 3 }}, + 'email': null } }; @@ -350,8 +355,9 @@ describe('parse()', function () { var tempBuffer = global.Buffer; delete global.Buffer; - expect(Qs.parse('a=b&c=d')).to.deep.equal({ a: 'b', c: 'd' }); + var result = Qs.parse('a=b&c=d'); global.Buffer = tempBuffer; + expect(result).to.deep.equal({ a: 'b', c: 'd' }); done(); }); @@ -371,10 +377,10 @@ describe('parse()', function () { expect(function () { parsed = Qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); - }).to.not.throw(Error); + }).to.not.throw(); - expect(parsed).to.have.key('foo'); - expect(parsed.foo).to.have.keys('bar', 'baz'); + expect(parsed).to.contain('foo'); + expect(parsed.foo).to.contain('bar', 'baz'); expect(parsed.foo.bar).to.equal('baz'); expect(parsed.foo.baz).to.deep.equal(a); done(); @@ -386,7 +392,9 @@ describe('parse()', function () { a.b = 'c'; expect(Qs.parse(a)).to.deep.equal({ b: 'c' }); - expect(Qs.parse({ a: a })).to.deep.equal({ a: { b: 'c' } }); + var result = Qs.parse({ a: a }); + expect(result).to.contain('a'); + expect(result.a).to.deep.equal(a); done(); }); diff --git a/server/node_modules/express/node_modules/qs/test/stringify.js b/server/node_modules/express/node_modules/qs/test/stringify.js index e8280041..7bdec329 100755 --- a/server/node_modules/express/node_modules/qs/test/stringify.js +++ b/server/node_modules/express/node_modules/qs/test/stringify.js @@ -1,5 +1,7 @@ +/* eslint no-extend-native:0 */ // Load modules +var Code = require('code'); var Lab = require('lab'); var Qs = require('../'); @@ -12,7 +14,7 @@ var internals = {}; // Test shortcuts var lab = exports.lab = Lab.script(); -var expect = Lab.expect; +var expect = Code.expect; var describe = lab.experiment; var it = lab.test; @@ -65,6 +67,36 @@ describe('stringify()', function () { done(); }); + it('uses indices notation for arrays when indices=true', function (done) { + + expect(Qs.stringify({ a: ['b', 'c'] }, { indices: true })).to.equal('a%5B0%5D=b&a%5B1%5D=c'); + done(); + }); + + it('uses indices notation for arrays when no arrayFormat is specified', function (done) { + + expect(Qs.stringify({ a: ['b', 'c'] })).to.equal('a%5B0%5D=b&a%5B1%5D=c'); + done(); + }); + + it('uses indices notation for arrays when no arrayFormat=indices', function (done) { + + expect(Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })).to.equal('a%5B0%5D=b&a%5B1%5D=c'); + done(); + }); + + it('uses repeat notation for arrays when no arrayFormat=repeat', function (done) { + + expect(Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })).to.equal('a=b&a=c'); + done(); + }); + + it('uses brackets notation for arrays when no arrayFormat=brackets', function (done) { + + expect(Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })).to.equal('a%5B%5D=b&a%5B%5D=c'); + done(); + }); + it('stringifies a complicated object', function (done) { expect(Qs.stringify({ a: { b: 'c', d: 'e' } })).to.equal('a%5Bb%5D=c&a%5Bd%5D=e'); diff --git a/server/node_modules/express/node_modules/range-parser/HISTORY.md b/server/node_modules/express/node_modules/range-parser/HISTORY.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/range-parser/LICENSE b/server/node_modules/express/node_modules/range-parser/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/range-parser/README.md b/server/node_modules/express/node_modules/range-parser/README.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/range-parser/index.js b/server/node_modules/express/node_modules/range-parser/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/range-parser/package.json b/server/node_modules/express/node_modules/range-parser/package.json old mode 100755 new mode 100644 index 9fc243b3..e680d61c --- a/server/node_modules/express/node_modules/range-parser/package.json +++ b/server/node_modules/express/node_modules/range-parser/package.json @@ -15,7 +15,7 @@ ], "repository": { "type": "git", - "url": "https://github.com/jshttp/range-parser" + "url": "git://github.com/jshttp/range-parser" }, "devDependencies": { "istanbul": "0", @@ -35,42 +35,11 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --require should", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot --require should" }, - "gitHead": "ae23b02ce705b56e7f7c48e832d41fa710227ecc", + "readme": "# range-parser\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nRange header field parser.\n\n## Installation\n\n```\n$ npm install range-parser\n```\n\n## Examples\n\n```js\nassert(-1 == parse(200, 'bytes=500-20'));\nassert(-2 == parse(200, 'bytes=malformed'));\nparse(200, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 199 }]));\nparse(1000, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 499 }]));\nparse(1000, 'bytes=40-80').should.eql(arr('bytes', [{ start: 40, end: 80 }]));\nparse(1000, 'bytes=-500').should.eql(arr('bytes', [{ start: 500, end: 999 }]));\nparse(1000, 'bytes=-400').should.eql(arr('bytes', [{ start: 600, end: 999 }]));\nparse(1000, 'bytes=500-').should.eql(arr('bytes', [{ start: 500, end: 999 }]));\nparse(1000, 'bytes=400-').should.eql(arr('bytes', [{ start: 400, end: 999 }]));\nparse(1000, 'bytes=0-0').should.eql(arr('bytes', [{ start: 0, end: 0 }]));\nparse(1000, 'bytes=-1').should.eql(arr('bytes', [{ start: 999, end: 999 }]));\nparse(1000, 'items=0-5').should.eql(arr('items', [{ start: 0, end: 5 }]));\nparse(1000, 'bytes=40-80,-1').should.eql(arr('bytes', [{ start: 40, end: 80 }, { start: 999, end: 999 }]));\n```\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/range-parser.svg?style=flat\n[npm-url]: https://npmjs.org/package/range-parser\n[node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/range-parser.svg?style=flat\n[travis-url]: https://travis-ci.org/jshttp/range-parser\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/range-parser.svg?style=flat\n[coveralls-url]: https://coveralls.io/r/jshttp/range-parser\n[downloads-image]: https://img.shields.io/npm/dm/range-parser.svg?style=flat\n[downloads-url]: https://npmjs.org/package/range-parser\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/range-parser/issues" }, - "homepage": "https://github.com/jshttp/range-parser", "_id": "range-parser@1.0.2", - "_shasum": "06a12a42e5131ba8e457cd892044867f2344e549", - "_from": "range-parser@~1.0.2", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "jonathanong", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - } - ], - "dist": { - "shasum": "06a12a42e5131ba8e457cd892044867f2344e549", - "tarball": "http://registry.npmjs.org/range-parser/-/range-parser-1.0.2.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.0.2.tgz", - "readme": "ERROR: No README data found!" + "_from": "range-parser@~1.0.2" } diff --git a/server/node_modules/express/node_modules/send/History.md b/server/node_modules/express/node_modules/send/History.md deleted file mode 100755 index ad5efc59..00000000 --- a/server/node_modules/express/node_modules/send/History.md +++ /dev/null @@ -1,221 +0,0 @@ -0.10.1 / 2014-10-22 -=================== - - * deps: on-finished@~2.1.1 - - Fix handling of pipelined requests - -0.10.0 / 2014-10-15 -=================== - - * deps: debug@~2.1.0 - - Implement `DEBUG_FD` env variable support - * deps: depd@~1.0.0 - * deps: etag@~1.5.0 - - Improve string performance - - Slightly improve speed for weak ETags over 1KB - -0.9.3 / 2014-09-24 -================== - - * deps: etag@~1.4.0 - - Support "fake" stats objects - -0.9.2 / 2014-09-15 -================== - - * deps: depd@0.4.5 - * deps: etag@~1.3.1 - * deps: range-parser@~1.0.2 - -0.9.1 / 2014-09-07 -================== - - * deps: fresh@0.2.4 - -0.9.0 / 2014-09-07 -================== - - * Add `lastModified` option - * Use `etag` to generate `ETag` header - * deps: debug@~2.0.0 - -0.8.5 / 2014-09-04 -================== - - * Fix malicious path detection for empty string path - -0.8.4 / 2014-09-04 -================== - - * Fix a path traversal issue when using `root` - -0.8.3 / 2014-08-16 -================== - - * deps: destroy@1.0.3 - - renamed from dethroy - * deps: on-finished@2.1.0 - -0.8.2 / 2014-08-14 -================== - - * Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` - * deps: dethroy@1.0.2 - -0.8.1 / 2014-08-05 -================== - - * Fix `extensions` behavior when file already has extension - -0.8.0 / 2014-08-05 -================== - - * Add `extensions` option - -0.7.4 / 2014-08-04 -================== - - * Fix serving index files without root dir - -0.7.3 / 2014-07-29 -================== - - * Fix incorrect 403 on Windows and Node.js 0.11 - -0.7.2 / 2014-07-27 -================== - - * deps: depd@0.4.4 - - Work-around v8 generating empty stack traces - -0.7.1 / 2014-07-26 -================== - - * deps: depd@0.4.3 - - Fix exception when global `Error.stackTraceLimit` is too low - -0.7.0 / 2014-07-20 -================== - - * Deprecate `hidden` option; use `dotfiles` option - * Add `dotfiles` option - * deps: debug@1.0.4 - * deps: depd@0.4.2 - - Add `TRACE_DEPRECATION` environment variable - - Remove non-standard grey color from color output - - Support `--no-deprecation` argument - - Support `--trace-deprecation` argument - -0.6.0 / 2014-07-11 -================== - - * Deprecate `from` option; use `root` option - * Deprecate `send.etag()` -- use `etag` in `options` - * Deprecate `send.hidden()` -- use `hidden` in `options` - * Deprecate `send.index()` -- use `index` in `options` - * Deprecate `send.maxage()` -- use `maxAge` in `options` - * Deprecate `send.root()` -- use `root` in `options` - * Cap `maxAge` value to 1 year - * deps: debug@1.0.3 - - Add support for multiple wildcards in namespaces - -0.5.0 / 2014-06-28 -================== - - * Accept string for `maxAge` (converted by `ms`) - * Add `headers` event - * Include link in default redirect response - * Use `EventEmitter.listenerCount` to count listeners - -0.4.3 / 2014-06-11 -================== - - * Do not throw un-catchable error on file open race condition - * Use `escape-html` for HTML escaping - * deps: debug@1.0.2 - - fix some debugging output colors on node.js 0.8 - * deps: finished@1.2.2 - * deps: fresh@0.2.2 - -0.4.2 / 2014-06-09 -================== - - * fix "event emitter leak" warnings - * deps: debug@1.0.1 - * deps: finished@1.2.1 - -0.4.1 / 2014-06-02 -================== - - * Send `max-age` in `Cache-Control` in correct format - -0.4.0 / 2014-05-27 -================== - - * Calculate ETag with md5 for reduced collisions - * Fix wrong behavior when index file matches directory - * Ignore stream errors after request ends - - Goodbye `EBADF, read` - * Skip directories in index file search - * deps: debug@0.8.1 - -0.3.0 / 2014-04-24 -================== - - * Fix sending files with dots without root set - * Coerce option types - * Accept API options in options object - * Set etags to "weak" - * Include file path in etag - * Make "Can't set headers after they are sent." catchable - * Send full entity-body for multi range requests - * Default directory access to 403 when index disabled - * Support multiple index paths - * Support "If-Range" header - * Control whether to generate etags - * deps: mime@1.2.11 - -0.2.0 / 2014-01-29 -================== - - * update range-parser and fresh - -0.1.4 / 2013-08-11 -================== - - * update fresh - -0.1.3 / 2013-07-08 -================== - - * Revert "Fix fd leak" - -0.1.2 / 2013-07-03 -================== - - * Fix fd leak - -0.1.0 / 2012-08-25 -================== - - * add options parameter to send() that is passed to fs.createReadStream() [kanongil] - -0.0.4 / 2012-08-16 -================== - - * allow custom "Accept-Ranges" definition - -0.0.3 / 2012-07-16 -================== - - * fix normalization of the root directory. Closes #3 - -0.0.2 / 2012-07-09 -================== - - * add passing of req explicitly for now (YUCK) - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/server/node_modules/express/node_modules/send/LICENSE b/server/node_modules/express/node_modules/send/LICENSE old mode 100755 new mode 100644 index 3b87e2db..e4d595b3 --- a/server/node_modules/express/node_modules/send/LICENSE +++ b/server/node_modules/express/node_modules/send/LICENSE @@ -1,7 +1,7 @@ (The MIT License) Copyright (c) 2012 TJ Holowaychuk -Copyright (c) 2014 Douglas Christopher Wilson +Copyright (c) 2014-2015 Douglas Christopher Wilson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/server/node_modules/express/node_modules/send/Readme.md b/server/node_modules/express/node_modules/send/Readme.md deleted file mode 100755 index 78bd40da..00000000 --- a/server/node_modules/express/node_modules/send/Readme.md +++ /dev/null @@ -1,182 +0,0 @@ -# send - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] -[![Gittip][gittip-image]][gittip-url] - - Send is Connect's `static()` extracted for generalized use, a streaming static file - server supporting partial responses (Ranges), conditional-GET negotiation, high test coverage, and granular events which may be leveraged to take appropriate actions in your application or framework. - -## Installation - -```bash -$ npm install send -``` - -## API - -```js -var send = require('send') -``` - -### send(req, path, [options]) - -Create a new `SendStream` for the given path to send to a `res`. The `req` is -the Node.js HTTP request and the `path` is a urlencoded path to send (urlencoded, -not the actual file-system path). - -#### Options - -##### dotfiles - - Set how "dotfiles" are treated when encountered. A dotfile is a file - or directory that begins with a dot ("."). Note this check is done on - the path itself without checking if the path actually exists on the - disk. If `root` is specified, only the dotfiles above the root are - checked (i.e. the root itself can be within a dotfile when when set - to "deny"). - - The default value is `'ignore'`. - - - `'allow'` No special treatment for dotfiles. - - `'deny'` Send a 403 for any request for a dotfile. - - `'ignore'` Pretend like the dotfile does not exist and 404. - -##### etag - - Enable or disable etag generation, defaults to true. - -##### extensions - - If a given file doesn't exist, try appending one of the given extensions, - in the given order. By default, this is disabled (set to `false`). An - example value that will serve extension-less HTML files: `['html', 'htm']`. - This is skipped if the requested file already has an extension. - -##### index - - By default send supports "index.html" files, to disable this - set `false` or to supply a new index pass a string or an array - in preferred order. - -##### lastModified - - Enable or disable `Last-Modified` header, defaults to true. Uses the file - system's last modified value. - -##### maxAge - - Provide a max-age in milliseconds for http caching, defaults to 0. - This can also be a string accepted by the - [ms](https://www.npmjs.org/package/ms#readme) module. - -##### root - - Serve files relative to `path`. - -### Events - -The `SendStream` is an event emitter and will emit the following events: - - - `error` an error occurred `(err)` - - `directory` a directory was requested - - `file` a file was requested `(path, stat)` - - `headers` the headers are about to be set on a file `(res, path, stat)` - - `stream` file streaming has started `(stream)` - - `end` streaming has completed - -### .pipe - -The `pipe` method is used to pipe the response into the Node.js HTTP response -object, typically `send(req, path, options).pipe(res)`. - -## Error-handling - - By default when no `error` listeners are present an automatic response will be made, otherwise you have full control over the response, aka you may show a 5xx page etc. - -## Caching - - It does _not_ perform internal caching, you should use a reverse proxy cache such - as Varnish for this, or those fancy things called CDNs. If your application is small enough that it would benefit from single-node memory caching, it's small enough that it does not need caching at all ;). - -## Debugging - - To enable `debug()` instrumentation output export __DEBUG__: - -``` -$ DEBUG=send node app -``` - -## Running tests - -``` -$ npm install -$ npm test -``` - -## Examples - - Small: - -```js -var http = require('http'); -var send = require('send'); - -var app = http.createServer(function(req, res){ - send(req, req.url).pipe(res); -}).listen(3000); -``` - - Serving from a root directory with custom error-handling: - -```js -var http = require('http'); -var send = require('send'); -var url = require('url'); - -var app = http.createServer(function(req, res){ - // your custom error-handling logic: - function error(err) { - res.statusCode = err.status || 500; - res.end(err.message); - } - - // your custom headers - function headers(res, path, stat) { - // serve all files for download - res.setHeader('Content-Disposition', 'attachment'); - } - - // your custom directory handling logic: - function redirect() { - res.statusCode = 301; - res.setHeader('Location', req.url + '/'); - res.end('Redirecting to ' + req.url + '/'); - } - - // transfer arbitrary files from within - // /www/example.com/public/* - send(req, url.parse(req.url).pathname, {root: '/www/example.com/public'}) - .on('error', error) - .on('directory', redirect) - .on('headers', headers) - .pipe(res); -}).listen(3000); -``` - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/send.svg?style=flat -[npm-url]: https://npmjs.org/package/send -[travis-image]: https://img.shields.io/travis/tj/send.svg?style=flat -[travis-url]: https://travis-ci.org/tj/send -[coveralls-image]: https://img.shields.io/coveralls/tj/send.svg?style=flat -[coveralls-url]: https://coveralls.io/r/tj/send?branch=master -[downloads-image]: https://img.shields.io/npm/dm/send.svg?style=flat -[downloads-url]: https://npmjs.org/package/send -[gittip-image]: https://img.shields.io/gittip/dougwilson.svg?style=flat -[gittip-url]: https://www.gittip.com/dougwilson/ diff --git a/server/node_modules/express/node_modules/send/index.js b/server/node_modules/express/node_modules/send/index.js old mode 100755 new mode 100644 index 64b6d641..594ccc16 --- a/server/node_modules/express/node_modules/send/index.js +++ b/server/node_modules/express/node_modules/send/index.js @@ -1,3 +1,9 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ /** * Module dependencies. @@ -56,7 +62,7 @@ var listenerCount = EventEmitter.listenerCount * * @param {Request} req * @param {String} path - * @param {Object} options + * @param {object} [options] * @return {SendStream} * @api public */ @@ -70,53 +76,53 @@ function send(req, path, options) { * * @param {Request} req * @param {String} path - * @param {Object} options + * @param {object} [options] * @api private */ function SendStream(req, path, options) { - var self = this; - options = options || {}; - this.req = req; - this.path = path; - this.options = options; + var opts = options || {} - this._etag = options.etag !== undefined - ? Boolean(options.etag) + this.options = opts + this.path = path + this.req = req + + this._etag = opts.etag !== undefined + ? Boolean(opts.etag) : true - this._dotfiles = options.dotfiles !== undefined - ? options.dotfiles + this._dotfiles = opts.dotfiles !== undefined + ? opts.dotfiles : 'ignore' if (['allow', 'deny', 'ignore'].indexOf(this._dotfiles) === -1) { throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') } - this._hidden = Boolean(options.hidden) + this._hidden = Boolean(opts.hidden) - if ('hidden' in options) { + if (opts.hidden !== undefined) { deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') } // legacy support - if (!('dotfiles' in options)) { + if (opts.dotfiles === undefined) { this._dotfiles = undefined } - this._extensions = options.extensions !== undefined - ? normalizeList(options.extensions) + this._extensions = opts.extensions !== undefined + ? normalizeList(opts.extensions, 'extensions option') : [] - this._index = options.index !== undefined - ? normalizeList(options.index) + this._index = opts.index !== undefined + ? normalizeList(opts.index, 'index option') : ['index.html'] - this._lastModified = options.lastModified !== undefined - ? Boolean(options.lastModified) + this._lastModified = opts.lastModified !== undefined + ? Boolean(opts.lastModified) : true - this._maxage = options.maxAge || options.maxage + this._maxage = opts.maxAge || opts.maxage this._maxage = typeof this._maxage === 'string' ? ms(this._maxage) : Number(this._maxage) @@ -124,12 +130,12 @@ function SendStream(req, path, options) { ? Math.min(Math.max(0, this._maxage), maxMaxAge) : 0 - this._root = options.root - ? resolve(options.root) + this._root = opts.root + ? resolve(opts.root) : null - if (!this._root && options.from) { - this.from(options.from); + if (!this._root && opts.from) { + this.from(opts.from) } } @@ -180,7 +186,7 @@ SendStream.prototype.hidden = deprecate.function(function hidden(val) { */ SendStream.prototype.index = deprecate.function(function index(paths) { - var index = !paths ? [] : normalizeList(paths); + var index = !paths ? [] : normalizeList(paths, 'paths argument'); debug('index %o', paths); this._index = index; return this; @@ -415,16 +421,16 @@ SendStream.prototype.pipe = function(res){ var parts if (root !== null) { - // join / normalize from optional root dir - path = normalize(join(root, path)) - root = normalize(root + sep) - // malicious path - if ((path + sep).substr(0, root.length) !== root) { + if (upPathRegexp.test(normalize('.' + sep + path))) { debug('malicious path "%s"', path) return this.error(403) } + // join / normalize from optional root dir + path = normalize(join(root, path)) + root = normalize(root + sep) + // explode path parts parts = path.substr(root.length).split(sep) } else { @@ -482,8 +488,9 @@ SendStream.prototype.pipe = function(res){ */ SendStream.prototype.send = function(path, stat){ - var options = this.options; var len = stat.size; + var options = this.options + var opts = {} var res = this.res; var req = this.req; var ranges = req.headers.range; @@ -537,9 +544,6 @@ SendStream.prototype.send = function(path, stat){ if (-2 != ranges && ranges.length === 1) { debug('range %j', ranges); - options.start = offset + ranges[0].start; - options.end = offset + ranges[0].end; - // Content-Range res.statusCode = 206; res.setHeader('Content-Range', 'bytes ' @@ -548,17 +552,28 @@ SendStream.prototype.send = function(path, stat){ + ranges[0].end + '/' + len); - len = options.end - options.start + 1; + + offset += ranges[0].start; + len = ranges[0].end - ranges[0].start + 1; } } + // clone options + for (var prop in options) { + opts[prop] = options[prop] + } + + // set read options + opts.start = offset + opts.end = Math.max(offset, offset + len - 1) + // content-length res.setHeader('Content-Length', len); // HEAD support if ('HEAD' == req.method) return res.end(); - this.stream(path, options); + this.stream(path, opts) }; /** @@ -765,9 +780,18 @@ function decode(path) { * Normalize the index option into an array. * * @param {boolean|string|array} val - * @api private + * @param {string} name + * @private */ -function normalizeList(val){ - return [].concat(val || []) +function normalizeList(val, name) { + var list = [].concat(val || []) + + for (var i = 0; i < list.length; i++) { + if (typeof list[i] !== 'string') { + throw new TypeError(name + ' must be array of strings or false') + } + } + + return list } diff --git a/server/node_modules/express/node_modules/send/node_modules/destroy/README.md b/server/node_modules/express/node_modules/send/node_modules/destroy/README.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/send/node_modules/destroy/index.js b/server/node_modules/express/node_modules/send/node_modules/destroy/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/send/node_modules/destroy/package.json b/server/node_modules/express/node_modules/send/node_modules/destroy/package.json old mode 100755 new mode 100644 index 8a58cada..10821801 --- a/server/node_modules/express/node_modules/send/node_modules/destroy/package.json +++ b/server/node_modules/express/node_modules/send/node_modules/destroy/package.json @@ -16,7 +16,7 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/stream-utils/destroy" + "url": "git://github.com/stream-utils/destroy" }, "devDependencies": { "istanbul": "0", @@ -38,29 +38,11 @@ "leak", "fd" ], - "gitHead": "50af95ece4a70202f9301bc3edc8f9fdbbad0f26", + "readme": "# Destroy\n\n[![NPM version][npm-image]][npm-url]\n[![Build status][travis-image]][travis-url]\n[![Test coverage][coveralls-image]][coveralls-url]\n[![Dependency Status][david-image]][david-url]\n[![License][license-image]][license-url]\n[![Downloads][downloads-image]][downloads-url]\n[![Gittip][gittip-image]][gittip-url]\n\nDestroy a stream.\n\n## API\n\n```js\nvar destroy = require('destroy')\n\nvar fs = require('fs')\nvar stream = fs.createReadStream('package.json')\ndestroy(stream)\n```\n\n[npm-image]: https://img.shields.io/npm/v/destroy.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/destroy\n[github-tag]: http://img.shields.io/github/tag/stream-utils/destroy.svg?style=flat-square\n[github-url]: https://github.com/stream-utils/destroy/tags\n[travis-image]: https://img.shields.io/travis/stream-utils/destroy.svg?style=flat-square\n[travis-url]: https://travis-ci.org/stream-utils/destroy\n[coveralls-image]: https://img.shields.io/coveralls/stream-utils/destroy.svg?style=flat-square\n[coveralls-url]: https://coveralls.io/r/stream-utils/destroy?branch=master\n[david-image]: http://img.shields.io/david/stream-utils/destroy.svg?style=flat-square\n[david-url]: https://david-dm.org/stream-utils/destroy\n[license-image]: http://img.shields.io/npm/l/destroy.svg?style=flat-square\n[license-url]: LICENSE.md\n[downloads-image]: http://img.shields.io/npm/dm/destroy.svg?style=flat-square\n[downloads-url]: https://npmjs.org/package/destroy\n[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square\n[gittip-url]: https://www.gittip.com/jonathanong/\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/stream-utils/destroy/issues" }, - "homepage": "https://github.com/stream-utils/destroy", "_id": "destroy@1.0.3", - "_shasum": "b433b4724e71fd8551d9885174851c5fc377e2c9", - "_from": "destroy@1.0.3", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - } - ], - "dist": { - "shasum": "b433b4724e71fd8551d9885174851c5fc377e2c9", - "tarball": "http://registry.npmjs.org/destroy/-/destroy-1.0.3.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.3.tgz" + "_from": "destroy@1.0.3" } diff --git a/server/node_modules/express/node_modules/send/node_modules/mime/LICENSE b/server/node_modules/express/node_modules/send/node_modules/mime/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/send/node_modules/mime/README.md b/server/node_modules/express/node_modules/send/node_modules/mime/README.md old mode 100755 new mode 100644 index 6ca19bd1..506fbe55 --- a/server/node_modules/express/node_modules/send/node_modules/mime/README.md +++ b/server/node_modules/express/node_modules/send/node_modules/mime/README.md @@ -1,6 +1,6 @@ # mime -Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community. +Comprehensive MIME type mapping API based on mime-db module. ## Install @@ -8,17 +8,32 @@ Install with [npm](http://github.com/isaacs/npm): npm install mime +## Contributing / Testing + + npm run test + +## Command Line + + mime [path_string] + +E.g. + + > mime scripts/jquery.js + application/javascript + ## API - Queries ### mime.lookup(path) Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. - var mime = require('mime'); +```js +var mime = require('mime'); - mime.lookup('/path/to/file.txt'); // => 'text/plain' - mime.lookup('file.txt'); // => 'text/plain' - mime.lookup('.TXT'); // => 'text/plain' - mime.lookup('htm'); // => 'text/html' +mime.lookup('/path/to/file.txt'); // => 'text/plain' +mime.lookup('file.txt'); // => 'text/plain' +mime.lookup('.TXT'); // => 'text/plain' +mime.lookup('htm'); // => 'text/html' +``` ### mime.default_type Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) @@ -26,41 +41,50 @@ Sets the mime type returned when `mime.lookup` fails to find the extension searc ### mime.extension(type) Get the default extension for `type` - mime.extension('text/html'); // => 'html' - mime.extension('application/octet-stream'); // => 'bin' +```js +mime.extension('text/html'); // => 'html' +mime.extension('application/octet-stream'); // => 'bin' +``` ### mime.charsets.lookup() Map mime-type to charset - mime.charsets.lookup('text/plain'); // => 'UTF-8' +```js +mime.charsets.lookup('text/plain'); // => 'UTF-8' +``` (The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) ## API - Defining Custom Types -The following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types). +Custom type mappings can be added on a per-project basis via the following APIs. ### mime.define() Add custom mime/extension mappings - mime.define({ - 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], - 'application/x-my-type': ['x-mt', 'x-mtt'], - // etc ... - }); +```js +mime.define({ + 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], + 'application/x-my-type': ['x-mt', 'x-mtt'], + // etc ... +}); - mime.lookup('x-sft'); // => 'text/x-some-format' +mime.lookup('x-sft'); // => 'text/x-some-format' +``` The first entry in the extensions array is returned by `mime.extension()`. E.g. - mime.extension('text/x-some-format'); // => 'x-sf' +```js +mime.extension('text/x-some-format'); // => 'x-sf' +``` ### mime.load(filepath) Load mappings from an Apache ".types" format file - mime.load('./my_project.types'); - +```js +mime.load('./my_project.types'); +``` The .types file format is simple - See the `types` dir for examples. diff --git a/server/node_modules/express/node_modules/send/node_modules/mime/mime.js b/server/node_modules/express/node_modules/send/node_modules/mime/mime.js old mode 100755 new mode 100644 index 48be0c5e..341b6a5c --- a/server/node_modules/express/node_modules/send/node_modules/mime/mime.js +++ b/server/node_modules/express/node_modules/send/node_modules/mime/mime.js @@ -21,7 +21,6 @@ function Mime() { Mime.prototype.define = function (map) { for (var type in map) { var exts = map[type]; - for (var i = 0; i < exts.length; i++) { if (process.env.DEBUG_MIME && this.types[exts]) { console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + @@ -47,7 +46,6 @@ Mime.prototype.define = function (map) { * @param file (String) path of file to load. */ Mime.prototype.load = function(file) { - this._loading = file; // Read file and split into lines var map = {}, @@ -85,12 +83,8 @@ Mime.prototype.extension = function(mimeType) { // Default instance var mime = new Mime(); -// Load local copy of -// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types -mime.load(path.join(__dirname, 'types/mime.types')); - -// Load additional types from node.js community -mime.load(path.join(__dirname, 'types/node.types')); +// Define built-in types +mime.define(require('./types.json')); // Default type mime.default_type = mime.lookup('bin'); diff --git a/server/node_modules/express/node_modules/send/node_modules/mime/package.json b/server/node_modules/express/node_modules/send/node_modules/mime/package.json old mode 100755 new mode 100644 index 3ab7acc4..86d4a1a8 --- a/server/node_modules/express/node_modules/send/node_modules/mime/package.json +++ b/server/node_modules/express/node_modules/send/node_modules/mime/package.json @@ -4,6 +4,13 @@ "email": "robert@broofa.com", "url": "http://github.com/broofa" }, + "scripts": { + "prepublish": "node build/build.js > types.json", + "test": "node build/test.js" + }, + "bin": { + "mime": "cli.js" + }, "contributors": [ { "name": "Benjamin Thomas", @@ -11,9 +18,17 @@ "url": "http://github.com/bentomas" } ], - "dependencies": {}, "description": "A comprehensive library for mime-type mapping", - "devDependencies": {}, + "licenses": [ + { + "type": "MIT", + "url": "https://raw.github.com/broofa/node-mime/master/LICENSE" + } + ], + "dependencies": {}, + "devDependencies": { + "mime-db": "^1.2.0" + }, "keywords": [ "util", "mime" @@ -24,32 +39,16 @@ "url": "https://github.com/broofa/node-mime", "type": "git" }, - "version": "1.2.11", + "version": "1.3.4", + "readme": "# mime\n\nComprehensive MIME type mapping API based on mime-db module.\n\n## Install\n\nInstall with [npm](http://github.com/isaacs/npm):\n\n npm install mime\n\n## Contributing / Testing\n\n npm run test\n\n## Command Line\n\n mime [path_string]\n\nE.g.\n\n > mime scripts/jquery.js\n application/javascript\n\n## API - Queries\n\n### mime.lookup(path)\nGet the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g.\n\n```js\nvar mime = require('mime');\n\nmime.lookup('/path/to/file.txt'); // => 'text/plain'\nmime.lookup('file.txt'); // => 'text/plain'\nmime.lookup('.TXT'); // => 'text/plain'\nmime.lookup('htm'); // => 'text/html'\n```\n\n### mime.default_type\nSets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.)\n\n### mime.extension(type)\nGet the default extension for `type`\n\n```js\nmime.extension('text/html'); // => 'html'\nmime.extension('application/octet-stream'); // => 'bin'\n```\n\n### mime.charsets.lookup()\n\nMap mime-type to charset\n\n```js\nmime.charsets.lookup('text/plain'); // => 'UTF-8'\n```\n\n(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.)\n\n## API - Defining Custom Types\n\nCustom type mappings can be added on a per-project basis via the following APIs.\n\n### mime.define()\n\nAdd custom mime/extension mappings\n\n```js\nmime.define({\n 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'],\n 'application/x-my-type': ['x-mt', 'x-mtt'],\n // etc ...\n});\n\nmime.lookup('x-sft'); // => 'text/x-some-format'\n```\n\nThe first entry in the extensions array is returned by `mime.extension()`. E.g.\n\n```js\nmime.extension('text/x-some-format'); // => 'x-sf'\n```\n\n### mime.load(filepath)\n\nLoad mappings from an Apache \".types\" format file\n\n```js\nmime.load('./my_project.types');\n```\nThe .types file format is simple - See the `types` dir for examples.\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/broofa/node-mime/issues" }, - "_id": "mime@1.2.11", + "_id": "mime@1.3.4", "dist": { - "shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", - "tarball": "http://registry.npmjs.org/mime/-/mime-1.2.11.tgz" + "shasum": "db2e4d34e4dd2b6daefec43455d6e0cf0bbea83d" }, - "_from": "mime@1.2.11", - "_npmVersion": "1.3.6", - "_npmUser": { - "name": "broofa", - "email": "robert@broofa.com" - }, - "maintainers": [ - { - "name": "broofa", - "email": "robert@broofa.com" - }, - { - "name": "bentomas", - "email": "benjamin@benjaminthomas.org" - } - ], - "directories": {}, - "_shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", - "_resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz" + "_from": "mime@1.3.4", + "_resolved": "https://registry.npmjs.org/mime/-/mime-1.3.4.tgz" } diff --git a/server/node_modules/express/node_modules/send/node_modules/mime/test.js b/server/node_modules/express/node_modules/send/node_modules/mime/test.js deleted file mode 100755 index 2cda1c7a..00000000 --- a/server/node_modules/express/node_modules/send/node_modules/mime/test.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Usage: node test.js - */ - -var mime = require('./mime'); -var assert = require('assert'); -var path = require('path'); - -function eq(a, b) { - console.log('Test: ' + a + ' === ' + b); - assert.strictEqual.apply(null, arguments); -} - -console.log(Object.keys(mime.extensions).length + ' types'); -console.log(Object.keys(mime.types).length + ' extensions\n'); - -// -// Test mime lookups -// - -eq('text/plain', mime.lookup('text.txt')); // normal file -eq('text/plain', mime.lookup('TEXT.TXT')); // uppercase -eq('text/plain', mime.lookup('dir/text.txt')); // dir + file -eq('text/plain', mime.lookup('.text.txt')); // hidden file -eq('text/plain', mime.lookup('.txt')); // nameless -eq('text/plain', mime.lookup('txt')); // extension-only -eq('text/plain', mime.lookup('/txt')); // extension-less () -eq('text/plain', mime.lookup('\\txt')); // Windows, extension-less -eq('application/octet-stream', mime.lookup('text.nope')); // unrecognized -eq('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default - -// -// Test extensions -// - -eq('txt', mime.extension(mime.types.text)); -eq('html', mime.extension(mime.types.htm)); -eq('bin', mime.extension('application/octet-stream')); -eq('bin', mime.extension('application/octet-stream ')); -eq('html', mime.extension(' text/html; charset=UTF-8')); -eq('html', mime.extension('text/html; charset=UTF-8 ')); -eq('html', mime.extension('text/html; charset=UTF-8')); -eq('html', mime.extension('text/html ; charset=UTF-8')); -eq('html', mime.extension('text/html;charset=UTF-8')); -eq('html', mime.extension('text/Html;charset=UTF-8')); -eq(undefined, mime.extension('unrecognized')); - -// -// Test node.types lookups -// - -eq('application/font-woff', mime.lookup('file.woff')); -eq('application/octet-stream', mime.lookup('file.buffer')); -eq('audio/mp4', mime.lookup('file.m4a')); -eq('font/opentype', mime.lookup('file.otf')); - -// -// Test charsets -// - -eq('UTF-8', mime.charsets.lookup('text/plain')); -eq(undefined, mime.charsets.lookup(mime.types.js)); -eq('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); - -// -// Test for overlaps between mime.types and node.types -// - -var apacheTypes = new mime.Mime(), nodeTypes = new mime.Mime(); -apacheTypes.load(path.join(__dirname, 'types/mime.types')); -nodeTypes.load(path.join(__dirname, 'types/node.types')); - -var keys = [].concat(Object.keys(apacheTypes.types)) - .concat(Object.keys(nodeTypes.types)); -keys.sort(); -for (var i = 1; i < keys.length; i++) { - if (keys[i] == keys[i-1]) { - console.warn('Warning: ' + - 'node.types defines ' + keys[i] + '->' + nodeTypes.types[keys[i]] + - ', mime.types defines ' + keys[i] + '->' + apacheTypes.types[keys[i]]); - } -} - -console.log('\nOK'); diff --git a/server/node_modules/express/node_modules/send/node_modules/mime/types/mime.types b/server/node_modules/express/node_modules/send/node_modules/mime/types/mime.types deleted file mode 100755 index da8cd691..00000000 --- a/server/node_modules/express/node_modules/send/node_modules/mime/types/mime.types +++ /dev/null @@ -1,1588 +0,0 @@ -# This file maps Internet media types to unique file extension(s). -# Although created for httpd, this file is used by many software systems -# and has been placed in the public domain for unlimited redisribution. -# -# The table below contains both registered and (common) unregistered types. -# A type that has no unique extension can be ignored -- they are listed -# here to guide configurations toward known types and to make it easier to -# identify "new" types. File extensions are also commonly used to indicate -# content languages and encodings, so choose them carefully. -# -# Internet media types should be registered as described in RFC 4288. -# The registry is at . -# -# MIME type (lowercased) Extensions -# ============================================ ========== -# application/1d-interleaved-parityfec -# application/3gpp-ims+xml -# application/activemessage -application/andrew-inset ez -# application/applefile -application/applixware aw -application/atom+xml atom -application/atomcat+xml atomcat -# application/atomicmail -application/atomsvc+xml atomsvc -# application/auth-policy+xml -# application/batch-smtp -# application/beep+xml -# application/calendar+xml -# application/cals-1840 -# application/ccmp+xml -application/ccxml+xml ccxml -application/cdmi-capability cdmia -application/cdmi-container cdmic -application/cdmi-domain cdmid -application/cdmi-object cdmio -application/cdmi-queue cdmiq -# application/cea-2018+xml -# application/cellml+xml -# application/cfw -# application/cnrp+xml -# application/commonground -# application/conference-info+xml -# application/cpl+xml -# application/csta+xml -# application/cstadata+xml -application/cu-seeme cu -# application/cybercash -application/davmount+xml davmount -# application/dca-rft -# application/dec-dx -# application/dialog-info+xml -# application/dicom -# application/dns -application/docbook+xml dbk -# application/dskpp+xml -application/dssc+der dssc -application/dssc+xml xdssc -# application/dvcs -application/ecmascript ecma -# application/edi-consent -# application/edi-x12 -# application/edifact -application/emma+xml emma -# application/epp+xml -application/epub+zip epub -# application/eshop -# application/example -application/exi exi -# application/fastinfoset -# application/fastsoap -# application/fits -application/font-tdpfr pfr -# application/framework-attributes+xml -application/gml+xml gml -application/gpx+xml gpx -application/gxf gxf -# application/h224 -# application/held+xml -# application/http -application/hyperstudio stk -# application/ibe-key-request+xml -# application/ibe-pkg-reply+xml -# application/ibe-pp-data -# application/iges -# application/im-iscomposing+xml -# application/index -# application/index.cmd -# application/index.obj -# application/index.response -# application/index.vnd -application/inkml+xml ink inkml -# application/iotp -application/ipfix ipfix -# application/ipp -# application/isup -application/java-archive jar -application/java-serialized-object ser -application/java-vm class -application/javascript js -application/json json -application/jsonml+json jsonml -# application/kpml-request+xml -# application/kpml-response+xml -application/lost+xml lostxml -application/mac-binhex40 hqx -application/mac-compactpro cpt -# application/macwriteii -application/mads+xml mads -application/marc mrc -application/marcxml+xml mrcx -application/mathematica ma nb mb -# application/mathml-content+xml -# application/mathml-presentation+xml -application/mathml+xml mathml -# application/mbms-associated-procedure-description+xml -# application/mbms-deregister+xml -# application/mbms-envelope+xml -# application/mbms-msk+xml -# application/mbms-msk-response+xml -# application/mbms-protection-description+xml -# application/mbms-reception-report+xml -# application/mbms-register+xml -# application/mbms-register-response+xml -# application/mbms-user-service-description+xml -application/mbox mbox -# application/media_control+xml -application/mediaservercontrol+xml mscml -application/metalink+xml metalink -application/metalink4+xml meta4 -application/mets+xml mets -# application/mikey -application/mods+xml mods -# application/moss-keys -# application/moss-signature -# application/mosskey-data -# application/mosskey-request -application/mp21 m21 mp21 -application/mp4 mp4s -# application/mpeg4-generic -# application/mpeg4-iod -# application/mpeg4-iod-xmt -# application/msc-ivr+xml -# application/msc-mixer+xml -application/msword doc dot -application/mxf mxf -# application/nasdata -# application/news-checkgroups -# application/news-groupinfo -# application/news-transmission -# application/nss -# application/ocsp-request -# application/ocsp-response -application/octet-stream bin dms lrf mar so dist distz pkg bpk dump elc deploy -application/oda oda -application/oebps-package+xml opf -application/ogg ogx -application/omdoc+xml omdoc -application/onenote onetoc onetoc2 onetmp onepkg -application/oxps oxps -# application/parityfec -application/patch-ops-error+xml xer -application/pdf pdf -application/pgp-encrypted pgp -# application/pgp-keys -application/pgp-signature asc sig -application/pics-rules prf -# application/pidf+xml -# application/pidf-diff+xml -application/pkcs10 p10 -application/pkcs7-mime p7m p7c -application/pkcs7-signature p7s -application/pkcs8 p8 -application/pkix-attr-cert ac -application/pkix-cert cer -application/pkix-crl crl -application/pkix-pkipath pkipath -application/pkixcmp pki -application/pls+xml pls -# application/poc-settings+xml -application/postscript ai eps ps -# application/prs.alvestrand.titrax-sheet -application/prs.cww cww -# application/prs.nprend -# application/prs.plucker -# application/prs.rdf-xml-crypt -# application/prs.xsf+xml -application/pskc+xml pskcxml -# application/qsig -application/rdf+xml rdf -application/reginfo+xml rif -application/relax-ng-compact-syntax rnc -# application/remote-printing -application/resource-lists+xml rl -application/resource-lists-diff+xml rld -# application/riscos -# application/rlmi+xml -application/rls-services+xml rs -application/rpki-ghostbusters gbr -application/rpki-manifest mft -application/rpki-roa roa -# application/rpki-updown -application/rsd+xml rsd -application/rss+xml rss -application/rtf rtf -# application/rtx -# application/samlassertion+xml -# application/samlmetadata+xml -application/sbml+xml sbml -application/scvp-cv-request scq -application/scvp-cv-response scs -application/scvp-vp-request spq -application/scvp-vp-response spp -application/sdp sdp -# application/set-payment -application/set-payment-initiation setpay -# application/set-registration -application/set-registration-initiation setreg -# application/sgml -# application/sgml-open-catalog -application/shf+xml shf -# application/sieve -# application/simple-filter+xml -# application/simple-message-summary -# application/simplesymbolcontainer -# application/slate -# application/smil -application/smil+xml smi smil -# application/soap+fastinfoset -# application/soap+xml -application/sparql-query rq -application/sparql-results+xml srx -# application/spirits-event+xml -application/srgs gram -application/srgs+xml grxml -application/sru+xml sru -application/ssdl+xml ssdl -application/ssml+xml ssml -# application/tamp-apex-update -# application/tamp-apex-update-confirm -# application/tamp-community-update -# application/tamp-community-update-confirm -# application/tamp-error -# application/tamp-sequence-adjust -# application/tamp-sequence-adjust-confirm -# application/tamp-status-query -# application/tamp-status-response -# application/tamp-update -# application/tamp-update-confirm -application/tei+xml tei teicorpus -application/thraud+xml tfi -# application/timestamp-query -# application/timestamp-reply -application/timestamped-data tsd -# application/tve-trigger -# application/ulpfec -# application/vcard+xml -# application/vemmi -# application/vividence.scriptfile -# application/vnd.3gpp.bsf+xml -application/vnd.3gpp.pic-bw-large plb -application/vnd.3gpp.pic-bw-small psb -application/vnd.3gpp.pic-bw-var pvb -# application/vnd.3gpp.sms -# application/vnd.3gpp2.bcmcsinfo+xml -# application/vnd.3gpp2.sms -application/vnd.3gpp2.tcap tcap -application/vnd.3m.post-it-notes pwn -application/vnd.accpac.simply.aso aso -application/vnd.accpac.simply.imp imp -application/vnd.acucobol acu -application/vnd.acucorp atc acutc -application/vnd.adobe.air-application-installer-package+zip air -application/vnd.adobe.formscentral.fcdt fcdt -application/vnd.adobe.fxp fxp fxpl -# application/vnd.adobe.partial-upload -application/vnd.adobe.xdp+xml xdp -application/vnd.adobe.xfdf xfdf -# application/vnd.aether.imp -# application/vnd.ah-barcode -application/vnd.ahead.space ahead -application/vnd.airzip.filesecure.azf azf -application/vnd.airzip.filesecure.azs azs -application/vnd.amazon.ebook azw -application/vnd.americandynamics.acc acc -application/vnd.amiga.ami ami -# application/vnd.amundsen.maze+xml -application/vnd.android.package-archive apk -application/vnd.anser-web-certificate-issue-initiation cii -application/vnd.anser-web-funds-transfer-initiation fti -application/vnd.antix.game-component atx -application/vnd.apple.installer+xml mpkg -application/vnd.apple.mpegurl m3u8 -# application/vnd.arastra.swi -application/vnd.aristanetworks.swi swi -application/vnd.astraea-software.iota iota -application/vnd.audiograph aep -# application/vnd.autopackage -# application/vnd.avistar+xml -application/vnd.blueice.multipass mpm -# application/vnd.bluetooth.ep.oob -application/vnd.bmi bmi -application/vnd.businessobjects rep -# application/vnd.cab-jscript -# application/vnd.canon-cpdl -# application/vnd.canon-lips -# application/vnd.cendio.thinlinc.clientconf -application/vnd.chemdraw+xml cdxml -application/vnd.chipnuts.karaoke-mmd mmd -application/vnd.cinderella cdy -# application/vnd.cirpack.isdn-ext -application/vnd.claymore cla -application/vnd.cloanto.rp9 rp9 -application/vnd.clonk.c4group c4g c4d c4f c4p c4u -application/vnd.cluetrust.cartomobile-config c11amc -application/vnd.cluetrust.cartomobile-config-pkg c11amz -# application/vnd.collection+json -# application/vnd.commerce-battelle -application/vnd.commonspace csp -application/vnd.contact.cmsg cdbcmsg -application/vnd.cosmocaller cmc -application/vnd.crick.clicker clkx -application/vnd.crick.clicker.keyboard clkk -application/vnd.crick.clicker.palette clkp -application/vnd.crick.clicker.template clkt -application/vnd.crick.clicker.wordbank clkw -application/vnd.criticaltools.wbs+xml wbs -application/vnd.ctc-posml pml -# application/vnd.ctct.ws+xml -# application/vnd.cups-pdf -# application/vnd.cups-postscript -application/vnd.cups-ppd ppd -# application/vnd.cups-raster -# application/vnd.cups-raw -# application/vnd.curl -application/vnd.curl.car car -application/vnd.curl.pcurl pcurl -# application/vnd.cybank -application/vnd.dart dart -application/vnd.data-vision.rdz rdz -application/vnd.dece.data uvf uvvf uvd uvvd -application/vnd.dece.ttml+xml uvt uvvt -application/vnd.dece.unspecified uvx uvvx -application/vnd.dece.zip uvz uvvz -application/vnd.denovo.fcselayout-link fe_launch -# application/vnd.dir-bi.plate-dl-nosuffix -application/vnd.dna dna -application/vnd.dolby.mlp mlp -# application/vnd.dolby.mobile.1 -# application/vnd.dolby.mobile.2 -application/vnd.dpgraph dpg -application/vnd.dreamfactory dfac -application/vnd.ds-keypoint kpxx -application/vnd.dvb.ait ait -# application/vnd.dvb.dvbj -# application/vnd.dvb.esgcontainer -# application/vnd.dvb.ipdcdftnotifaccess -# application/vnd.dvb.ipdcesgaccess -# application/vnd.dvb.ipdcesgaccess2 -# application/vnd.dvb.ipdcesgpdd -# application/vnd.dvb.ipdcroaming -# application/vnd.dvb.iptv.alfec-base -# application/vnd.dvb.iptv.alfec-enhancement -# application/vnd.dvb.notif-aggregate-root+xml -# application/vnd.dvb.notif-container+xml -# application/vnd.dvb.notif-generic+xml -# application/vnd.dvb.notif-ia-msglist+xml -# application/vnd.dvb.notif-ia-registration-request+xml -# application/vnd.dvb.notif-ia-registration-response+xml -# application/vnd.dvb.notif-init+xml -# application/vnd.dvb.pfr -application/vnd.dvb.service svc -# application/vnd.dxr -application/vnd.dynageo geo -# application/vnd.easykaraoke.cdgdownload -# application/vnd.ecdis-update -application/vnd.ecowin.chart mag -# application/vnd.ecowin.filerequest -# application/vnd.ecowin.fileupdate -# application/vnd.ecowin.series -# application/vnd.ecowin.seriesrequest -# application/vnd.ecowin.seriesupdate -# application/vnd.emclient.accessrequest+xml -application/vnd.enliven nml -# application/vnd.eprints.data+xml -application/vnd.epson.esf esf -application/vnd.epson.msf msf -application/vnd.epson.quickanime qam -application/vnd.epson.salt slt -application/vnd.epson.ssf ssf -# application/vnd.ericsson.quickcall -application/vnd.eszigno3+xml es3 et3 -# application/vnd.etsi.aoc+xml -# application/vnd.etsi.cug+xml -# application/vnd.etsi.iptvcommand+xml -# application/vnd.etsi.iptvdiscovery+xml -# application/vnd.etsi.iptvprofile+xml -# application/vnd.etsi.iptvsad-bc+xml -# application/vnd.etsi.iptvsad-cod+xml -# application/vnd.etsi.iptvsad-npvr+xml -# application/vnd.etsi.iptvservice+xml -# application/vnd.etsi.iptvsync+xml -# application/vnd.etsi.iptvueprofile+xml -# application/vnd.etsi.mcid+xml -# application/vnd.etsi.overload-control-policy-dataset+xml -# application/vnd.etsi.sci+xml -# application/vnd.etsi.simservs+xml -# application/vnd.etsi.tsl+xml -# application/vnd.etsi.tsl.der -# application/vnd.eudora.data -application/vnd.ezpix-album ez2 -application/vnd.ezpix-package ez3 -# application/vnd.f-secure.mobile -application/vnd.fdf fdf -application/vnd.fdsn.mseed mseed -application/vnd.fdsn.seed seed dataless -# application/vnd.ffsns -# application/vnd.fints -application/vnd.flographit gph -application/vnd.fluxtime.clip ftc -# application/vnd.font-fontforge-sfd -application/vnd.framemaker fm frame maker book -application/vnd.frogans.fnc fnc -application/vnd.frogans.ltf ltf -application/vnd.fsc.weblaunch fsc -application/vnd.fujitsu.oasys oas -application/vnd.fujitsu.oasys2 oa2 -application/vnd.fujitsu.oasys3 oa3 -application/vnd.fujitsu.oasysgp fg5 -application/vnd.fujitsu.oasysprs bh2 -# application/vnd.fujixerox.art-ex -# application/vnd.fujixerox.art4 -# application/vnd.fujixerox.hbpl -application/vnd.fujixerox.ddd ddd -application/vnd.fujixerox.docuworks xdw -application/vnd.fujixerox.docuworks.binder xbd -# application/vnd.fut-misnet -application/vnd.fuzzysheet fzs -application/vnd.genomatix.tuxedo txd -# application/vnd.geocube+xml -application/vnd.geogebra.file ggb -application/vnd.geogebra.tool ggt -application/vnd.geometry-explorer gex gre -application/vnd.geonext gxt -application/vnd.geoplan g2w -application/vnd.geospace g3w -# application/vnd.globalplatform.card-content-mgt -# application/vnd.globalplatform.card-content-mgt-response -application/vnd.gmx gmx -application/vnd.google-earth.kml+xml kml -application/vnd.google-earth.kmz kmz -application/vnd.grafeq gqf gqs -# application/vnd.gridmp -application/vnd.groove-account gac -application/vnd.groove-help ghf -application/vnd.groove-identity-message gim -application/vnd.groove-injector grv -application/vnd.groove-tool-message gtm -application/vnd.groove-tool-template tpl -application/vnd.groove-vcard vcg -# application/vnd.hal+json -application/vnd.hal+xml hal -application/vnd.handheld-entertainment+xml zmm -application/vnd.hbci hbci -# application/vnd.hcl-bireports -application/vnd.hhe.lesson-player les -application/vnd.hp-hpgl hpgl -application/vnd.hp-hpid hpid -application/vnd.hp-hps hps -application/vnd.hp-jlyt jlt -application/vnd.hp-pcl pcl -application/vnd.hp-pclxl pclxl -# application/vnd.httphone -application/vnd.hydrostatix.sof-data sfd-hdstx -# application/vnd.hzn-3d-crossword -# application/vnd.ibm.afplinedata -# application/vnd.ibm.electronic-media -application/vnd.ibm.minipay mpy -application/vnd.ibm.modcap afp listafp list3820 -application/vnd.ibm.rights-management irm -application/vnd.ibm.secure-container sc -application/vnd.iccprofile icc icm -application/vnd.igloader igl -application/vnd.immervision-ivp ivp -application/vnd.immervision-ivu ivu -# application/vnd.informedcontrol.rms+xml -# application/vnd.informix-visionary -# application/vnd.infotech.project -# application/vnd.infotech.project+xml -# application/vnd.innopath.wamp.notification -application/vnd.insors.igm igm -application/vnd.intercon.formnet xpw xpx -application/vnd.intergeo i2g -# application/vnd.intertrust.digibox -# application/vnd.intertrust.nncp -application/vnd.intu.qbo qbo -application/vnd.intu.qfx qfx -# application/vnd.iptc.g2.conceptitem+xml -# application/vnd.iptc.g2.knowledgeitem+xml -# application/vnd.iptc.g2.newsitem+xml -# application/vnd.iptc.g2.newsmessage+xml -# application/vnd.iptc.g2.packageitem+xml -# application/vnd.iptc.g2.planningitem+xml -application/vnd.ipunplugged.rcprofile rcprofile -application/vnd.irepository.package+xml irp -application/vnd.is-xpr xpr -application/vnd.isac.fcs fcs -application/vnd.jam jam -# application/vnd.japannet-directory-service -# application/vnd.japannet-jpnstore-wakeup -# application/vnd.japannet-payment-wakeup -# application/vnd.japannet-registration -# application/vnd.japannet-registration-wakeup -# application/vnd.japannet-setstore-wakeup -# application/vnd.japannet-verification -# application/vnd.japannet-verification-wakeup -application/vnd.jcp.javame.midlet-rms rms -application/vnd.jisp jisp -application/vnd.joost.joda-archive joda -application/vnd.kahootz ktz ktr -application/vnd.kde.karbon karbon -application/vnd.kde.kchart chrt -application/vnd.kde.kformula kfo -application/vnd.kde.kivio flw -application/vnd.kde.kontour kon -application/vnd.kde.kpresenter kpr kpt -application/vnd.kde.kspread ksp -application/vnd.kde.kword kwd kwt -application/vnd.kenameaapp htke -application/vnd.kidspiration kia -application/vnd.kinar kne knp -application/vnd.koan skp skd skt skm -application/vnd.kodak-descriptor sse -application/vnd.las.las+xml lasxml -# application/vnd.liberty-request+xml -application/vnd.llamagraphics.life-balance.desktop lbd -application/vnd.llamagraphics.life-balance.exchange+xml lbe -application/vnd.lotus-1-2-3 123 -application/vnd.lotus-approach apr -application/vnd.lotus-freelance pre -application/vnd.lotus-notes nsf -application/vnd.lotus-organizer org -application/vnd.lotus-screencam scm -application/vnd.lotus-wordpro lwp -application/vnd.macports.portpkg portpkg -# application/vnd.marlin.drm.actiontoken+xml -# application/vnd.marlin.drm.conftoken+xml -# application/vnd.marlin.drm.license+xml -# application/vnd.marlin.drm.mdcf -application/vnd.mcd mcd -application/vnd.medcalcdata mc1 -application/vnd.mediastation.cdkey cdkey -# application/vnd.meridian-slingshot -application/vnd.mfer mwf -application/vnd.mfmp mfm -application/vnd.micrografx.flo flo -application/vnd.micrografx.igx igx -application/vnd.mif mif -# application/vnd.minisoft-hp3000-save -# application/vnd.mitsubishi.misty-guard.trustweb -application/vnd.mobius.daf daf -application/vnd.mobius.dis dis -application/vnd.mobius.mbk mbk -application/vnd.mobius.mqy mqy -application/vnd.mobius.msl msl -application/vnd.mobius.plc plc -application/vnd.mobius.txf txf -application/vnd.mophun.application mpn -application/vnd.mophun.certificate mpc -# application/vnd.motorola.flexsuite -# application/vnd.motorola.flexsuite.adsi -# application/vnd.motorola.flexsuite.fis -# application/vnd.motorola.flexsuite.gotap -# application/vnd.motorola.flexsuite.kmr -# application/vnd.motorola.flexsuite.ttc -# application/vnd.motorola.flexsuite.wem -# application/vnd.motorola.iprm -application/vnd.mozilla.xul+xml xul -application/vnd.ms-artgalry cil -# application/vnd.ms-asf -application/vnd.ms-cab-compressed cab -# application/vnd.ms-color.iccprofile -application/vnd.ms-excel xls xlm xla xlc xlt xlw -application/vnd.ms-excel.addin.macroenabled.12 xlam -application/vnd.ms-excel.sheet.binary.macroenabled.12 xlsb -application/vnd.ms-excel.sheet.macroenabled.12 xlsm -application/vnd.ms-excel.template.macroenabled.12 xltm -application/vnd.ms-fontobject eot -application/vnd.ms-htmlhelp chm -application/vnd.ms-ims ims -application/vnd.ms-lrm lrm -# application/vnd.ms-office.activex+xml -application/vnd.ms-officetheme thmx -# application/vnd.ms-opentype -# application/vnd.ms-package.obfuscated-opentype -application/vnd.ms-pki.seccat cat -application/vnd.ms-pki.stl stl -# application/vnd.ms-playready.initiator+xml -application/vnd.ms-powerpoint ppt pps pot -application/vnd.ms-powerpoint.addin.macroenabled.12 ppam -application/vnd.ms-powerpoint.presentation.macroenabled.12 pptm -application/vnd.ms-powerpoint.slide.macroenabled.12 sldm -application/vnd.ms-powerpoint.slideshow.macroenabled.12 ppsm -application/vnd.ms-powerpoint.template.macroenabled.12 potm -# application/vnd.ms-printing.printticket+xml -application/vnd.ms-project mpp mpt -# application/vnd.ms-tnef -# application/vnd.ms-wmdrm.lic-chlg-req -# application/vnd.ms-wmdrm.lic-resp -# application/vnd.ms-wmdrm.meter-chlg-req -# application/vnd.ms-wmdrm.meter-resp -application/vnd.ms-word.document.macroenabled.12 docm -application/vnd.ms-word.template.macroenabled.12 dotm -application/vnd.ms-works wps wks wcm wdb -application/vnd.ms-wpl wpl -application/vnd.ms-xpsdocument xps -application/vnd.mseq mseq -# application/vnd.msign -# application/vnd.multiad.creator -# application/vnd.multiad.creator.cif -# application/vnd.music-niff -application/vnd.musician mus -application/vnd.muvee.style msty -application/vnd.mynfc taglet -# application/vnd.ncd.control -# application/vnd.ncd.reference -# application/vnd.nervana -# application/vnd.netfpx -application/vnd.neurolanguage.nlu nlu -application/vnd.nitf ntf nitf -application/vnd.noblenet-directory nnd -application/vnd.noblenet-sealer nns -application/vnd.noblenet-web nnw -# application/vnd.nokia.catalogs -# application/vnd.nokia.conml+wbxml -# application/vnd.nokia.conml+xml -# application/vnd.nokia.isds-radio-presets -# application/vnd.nokia.iptv.config+xml -# application/vnd.nokia.landmark+wbxml -# application/vnd.nokia.landmark+xml -# application/vnd.nokia.landmarkcollection+xml -# application/vnd.nokia.n-gage.ac+xml -application/vnd.nokia.n-gage.data ngdat -application/vnd.nokia.n-gage.symbian.install n-gage -# application/vnd.nokia.ncd -# application/vnd.nokia.pcd+wbxml -# application/vnd.nokia.pcd+xml -application/vnd.nokia.radio-preset rpst -application/vnd.nokia.radio-presets rpss -application/vnd.novadigm.edm edm -application/vnd.novadigm.edx edx -application/vnd.novadigm.ext ext -# application/vnd.ntt-local.file-transfer -# application/vnd.ntt-local.sip-ta_remote -# application/vnd.ntt-local.sip-ta_tcp_stream -application/vnd.oasis.opendocument.chart odc -application/vnd.oasis.opendocument.chart-template otc -application/vnd.oasis.opendocument.database odb -application/vnd.oasis.opendocument.formula odf -application/vnd.oasis.opendocument.formula-template odft -application/vnd.oasis.opendocument.graphics odg -application/vnd.oasis.opendocument.graphics-template otg -application/vnd.oasis.opendocument.image odi -application/vnd.oasis.opendocument.image-template oti -application/vnd.oasis.opendocument.presentation odp -application/vnd.oasis.opendocument.presentation-template otp -application/vnd.oasis.opendocument.spreadsheet ods -application/vnd.oasis.opendocument.spreadsheet-template ots -application/vnd.oasis.opendocument.text odt -application/vnd.oasis.opendocument.text-master odm -application/vnd.oasis.opendocument.text-template ott -application/vnd.oasis.opendocument.text-web oth -# application/vnd.obn -# application/vnd.oftn.l10n+json -# application/vnd.oipf.contentaccessdownload+xml -# application/vnd.oipf.contentaccessstreaming+xml -# application/vnd.oipf.cspg-hexbinary -# application/vnd.oipf.dae.svg+xml -# application/vnd.oipf.dae.xhtml+xml -# application/vnd.oipf.mippvcontrolmessage+xml -# application/vnd.oipf.pae.gem -# application/vnd.oipf.spdiscovery+xml -# application/vnd.oipf.spdlist+xml -# application/vnd.oipf.ueprofile+xml -# application/vnd.oipf.userprofile+xml -application/vnd.olpc-sugar xo -# application/vnd.oma-scws-config -# application/vnd.oma-scws-http-request -# application/vnd.oma-scws-http-response -# application/vnd.oma.bcast.associated-procedure-parameter+xml -# application/vnd.oma.bcast.drm-trigger+xml -# application/vnd.oma.bcast.imd+xml -# application/vnd.oma.bcast.ltkm -# application/vnd.oma.bcast.notification+xml -# application/vnd.oma.bcast.provisioningtrigger -# application/vnd.oma.bcast.sgboot -# application/vnd.oma.bcast.sgdd+xml -# application/vnd.oma.bcast.sgdu -# application/vnd.oma.bcast.simple-symbol-container -# application/vnd.oma.bcast.smartcard-trigger+xml -# application/vnd.oma.bcast.sprov+xml -# application/vnd.oma.bcast.stkm -# application/vnd.oma.cab-address-book+xml -# application/vnd.oma.cab-feature-handler+xml -# application/vnd.oma.cab-pcc+xml -# application/vnd.oma.cab-user-prefs+xml -# application/vnd.oma.dcd -# application/vnd.oma.dcdc -application/vnd.oma.dd2+xml dd2 -# application/vnd.oma.drm.risd+xml -# application/vnd.oma.group-usage-list+xml -# application/vnd.oma.pal+xml -# application/vnd.oma.poc.detailed-progress-report+xml -# application/vnd.oma.poc.final-report+xml -# application/vnd.oma.poc.groups+xml -# application/vnd.oma.poc.invocation-descriptor+xml -# application/vnd.oma.poc.optimized-progress-report+xml -# application/vnd.oma.push -# application/vnd.oma.scidm.messages+xml -# application/vnd.oma.xcap-directory+xml -# application/vnd.omads-email+xml -# application/vnd.omads-file+xml -# application/vnd.omads-folder+xml -# application/vnd.omaloc-supl-init -application/vnd.openofficeorg.extension oxt -# application/vnd.openxmlformats-officedocument.custom-properties+xml -# application/vnd.openxmlformats-officedocument.customxmlproperties+xml -# application/vnd.openxmlformats-officedocument.drawing+xml -# application/vnd.openxmlformats-officedocument.drawingml.chart+xml -# application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml -# application/vnd.openxmlformats-officedocument.extended-properties+xml -# application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml -# application/vnd.openxmlformats-officedocument.presentationml.comments+xml -# application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml -# application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml -# application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml -application/vnd.openxmlformats-officedocument.presentationml.presentation pptx -# application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.presprops+xml -application/vnd.openxmlformats-officedocument.presentationml.slide sldx -# application/vnd.openxmlformats-officedocument.presentationml.slide+xml -# application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml -# application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml -application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx -# application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml -# application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml -# application/vnd.openxmlformats-officedocument.presentationml.tags+xml -application/vnd.openxmlformats-officedocument.presentationml.template potx -# application/vnd.openxmlformats-officedocument.presentationml.template.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml -application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx -# application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml -application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx -# application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml -# application/vnd.openxmlformats-officedocument.theme+xml -# application/vnd.openxmlformats-officedocument.themeoverride+xml -# application/vnd.openxmlformats-officedocument.vmldrawing -# application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml -application/vnd.openxmlformats-officedocument.wordprocessingml.document docx -# application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml -application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx -# application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml -# application/vnd.openxmlformats-package.core-properties+xml -# application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml -# application/vnd.openxmlformats-package.relationships+xml -# application/vnd.quobject-quoxdocument -# application/vnd.osa.netdeploy -application/vnd.osgeo.mapguide.package mgp -# application/vnd.osgi.bundle -application/vnd.osgi.dp dp -application/vnd.osgi.subsystem esa -# application/vnd.otps.ct-kip+xml -application/vnd.palm pdb pqa oprc -# application/vnd.paos.xml -application/vnd.pawaafile paw -application/vnd.pg.format str -application/vnd.pg.osasli ei6 -# application/vnd.piaccess.application-licence -application/vnd.picsel efif -application/vnd.pmi.widget wg -# application/vnd.poc.group-advertisement+xml -application/vnd.pocketlearn plf -application/vnd.powerbuilder6 pbd -# application/vnd.powerbuilder6-s -# application/vnd.powerbuilder7 -# application/vnd.powerbuilder7-s -# application/vnd.powerbuilder75 -# application/vnd.powerbuilder75-s -# application/vnd.preminet -application/vnd.previewsystems.box box -application/vnd.proteus.magazine mgz -application/vnd.publishare-delta-tree qps -application/vnd.pvi.ptid1 ptid -# application/vnd.pwg-multiplexed -# application/vnd.pwg-xhtml-print+xml -# application/vnd.qualcomm.brew-app-res -application/vnd.quark.quarkxpress qxd qxt qwd qwt qxl qxb -# application/vnd.radisys.moml+xml -# application/vnd.radisys.msml+xml -# application/vnd.radisys.msml-audit+xml -# application/vnd.radisys.msml-audit-conf+xml -# application/vnd.radisys.msml-audit-conn+xml -# application/vnd.radisys.msml-audit-dialog+xml -# application/vnd.radisys.msml-audit-stream+xml -# application/vnd.radisys.msml-conf+xml -# application/vnd.radisys.msml-dialog+xml -# application/vnd.radisys.msml-dialog-base+xml -# application/vnd.radisys.msml-dialog-fax-detect+xml -# application/vnd.radisys.msml-dialog-fax-sendrecv+xml -# application/vnd.radisys.msml-dialog-group+xml -# application/vnd.radisys.msml-dialog-speech+xml -# application/vnd.radisys.msml-dialog-transform+xml -# application/vnd.rainstor.data -# application/vnd.rapid -application/vnd.realvnc.bed bed -application/vnd.recordare.musicxml mxl -application/vnd.recordare.musicxml+xml musicxml -# application/vnd.renlearn.rlprint -application/vnd.rig.cryptonote cryptonote -application/vnd.rim.cod cod -application/vnd.rn-realmedia rm -application/vnd.rn-realmedia-vbr rmvb -application/vnd.route66.link66+xml link66 -# application/vnd.rs-274x -# application/vnd.ruckus.download -# application/vnd.s3sms -application/vnd.sailingtracker.track st -# application/vnd.sbm.cid -# application/vnd.sbm.mid2 -# application/vnd.scribus -# application/vnd.sealed.3df -# application/vnd.sealed.csf -# application/vnd.sealed.doc -# application/vnd.sealed.eml -# application/vnd.sealed.mht -# application/vnd.sealed.net -# application/vnd.sealed.ppt -# application/vnd.sealed.tiff -# application/vnd.sealed.xls -# application/vnd.sealedmedia.softseal.html -# application/vnd.sealedmedia.softseal.pdf -application/vnd.seemail see -application/vnd.sema sema -application/vnd.semd semd -application/vnd.semf semf -application/vnd.shana.informed.formdata ifm -application/vnd.shana.informed.formtemplate itp -application/vnd.shana.informed.interchange iif -application/vnd.shana.informed.package ipk -application/vnd.simtech-mindmapper twd twds -application/vnd.smaf mmf -# application/vnd.smart.notebook -application/vnd.smart.teacher teacher -# application/vnd.software602.filler.form+xml -# application/vnd.software602.filler.form-xml-zip -application/vnd.solent.sdkm+xml sdkm sdkd -application/vnd.spotfire.dxp dxp -application/vnd.spotfire.sfs sfs -# application/vnd.sss-cod -# application/vnd.sss-dtf -# application/vnd.sss-ntf -application/vnd.stardivision.calc sdc -application/vnd.stardivision.draw sda -application/vnd.stardivision.impress sdd -application/vnd.stardivision.math smf -application/vnd.stardivision.writer sdw vor -application/vnd.stardivision.writer-global sgl -application/vnd.stepmania.package smzip -application/vnd.stepmania.stepchart sm -# application/vnd.street-stream -application/vnd.sun.xml.calc sxc -application/vnd.sun.xml.calc.template stc -application/vnd.sun.xml.draw sxd -application/vnd.sun.xml.draw.template std -application/vnd.sun.xml.impress sxi -application/vnd.sun.xml.impress.template sti -application/vnd.sun.xml.math sxm -application/vnd.sun.xml.writer sxw -application/vnd.sun.xml.writer.global sxg -application/vnd.sun.xml.writer.template stw -# application/vnd.sun.wadl+xml -application/vnd.sus-calendar sus susp -application/vnd.svd svd -# application/vnd.swiftview-ics -application/vnd.symbian.install sis sisx -application/vnd.syncml+xml xsm -application/vnd.syncml.dm+wbxml bdm -application/vnd.syncml.dm+xml xdm -# application/vnd.syncml.dm.notification -# application/vnd.syncml.ds.notification -application/vnd.tao.intent-module-archive tao -application/vnd.tcpdump.pcap pcap cap dmp -application/vnd.tmobile-livetv tmo -application/vnd.trid.tpt tpt -application/vnd.triscape.mxs mxs -application/vnd.trueapp tra -# application/vnd.truedoc -# application/vnd.ubisoft.webplayer -application/vnd.ufdl ufd ufdl -application/vnd.uiq.theme utz -application/vnd.umajin umj -application/vnd.unity unityweb -application/vnd.uoml+xml uoml -# application/vnd.uplanet.alert -# application/vnd.uplanet.alert-wbxml -# application/vnd.uplanet.bearer-choice -# application/vnd.uplanet.bearer-choice-wbxml -# application/vnd.uplanet.cacheop -# application/vnd.uplanet.cacheop-wbxml -# application/vnd.uplanet.channel -# application/vnd.uplanet.channel-wbxml -# application/vnd.uplanet.list -# application/vnd.uplanet.list-wbxml -# application/vnd.uplanet.listcmd -# application/vnd.uplanet.listcmd-wbxml -# application/vnd.uplanet.signal -application/vnd.vcx vcx -# application/vnd.vd-study -# application/vnd.vectorworks -# application/vnd.verimatrix.vcas -# application/vnd.vidsoft.vidconference -application/vnd.visio vsd vst vss vsw -application/vnd.visionary vis -# application/vnd.vividence.scriptfile -application/vnd.vsf vsf -# application/vnd.wap.sic -# application/vnd.wap.slc -application/vnd.wap.wbxml wbxml -application/vnd.wap.wmlc wmlc -application/vnd.wap.wmlscriptc wmlsc -application/vnd.webturbo wtb -# application/vnd.wfa.wsc -# application/vnd.wmc -# application/vnd.wmf.bootstrap -# application/vnd.wolfram.mathematica -# application/vnd.wolfram.mathematica.package -application/vnd.wolfram.player nbp -application/vnd.wordperfect wpd -application/vnd.wqd wqd -# application/vnd.wrq-hp3000-labelled -application/vnd.wt.stf stf -# application/vnd.wv.csp+wbxml -# application/vnd.wv.csp+xml -# application/vnd.wv.ssp+xml -application/vnd.xara xar -application/vnd.xfdl xfdl -# application/vnd.xfdl.webform -# application/vnd.xmi+xml -# application/vnd.xmpie.cpkg -# application/vnd.xmpie.dpkg -# application/vnd.xmpie.plan -# application/vnd.xmpie.ppkg -# application/vnd.xmpie.xlim -application/vnd.yamaha.hv-dic hvd -application/vnd.yamaha.hv-script hvs -application/vnd.yamaha.hv-voice hvp -application/vnd.yamaha.openscoreformat osf -application/vnd.yamaha.openscoreformat.osfpvg+xml osfpvg -# application/vnd.yamaha.remote-setup -application/vnd.yamaha.smaf-audio saf -application/vnd.yamaha.smaf-phrase spf -# application/vnd.yamaha.through-ngn -# application/vnd.yamaha.tunnel-udpencap -application/vnd.yellowriver-custom-menu cmp -application/vnd.zul zir zirz -application/vnd.zzazz.deck+xml zaz -application/voicexml+xml vxml -# application/vq-rtcpxr -# application/watcherinfo+xml -# application/whoispp-query -# application/whoispp-response -application/widget wgt -application/winhlp hlp -# application/wita -# application/wordperfect5.1 -application/wsdl+xml wsdl -application/wspolicy+xml wspolicy -application/x-7z-compressed 7z -application/x-abiword abw -application/x-ace-compressed ace -# application/x-amf -application/x-apple-diskimage dmg -application/x-authorware-bin aab x32 u32 vox -application/x-authorware-map aam -application/x-authorware-seg aas -application/x-bcpio bcpio -application/x-bittorrent torrent -application/x-blorb blb blorb -application/x-bzip bz -application/x-bzip2 bz2 boz -application/x-cbr cbr cba cbt cbz cb7 -application/x-cdlink vcd -application/x-cfs-compressed cfs -application/x-chat chat -application/x-chess-pgn pgn -application/x-conference nsc -# application/x-compress -application/x-cpio cpio -application/x-csh csh -application/x-debian-package deb udeb -application/x-dgc-compressed dgc -application/x-director dir dcr dxr cst cct cxt w3d fgd swa -application/x-doom wad -application/x-dtbncx+xml ncx -application/x-dtbook+xml dtb -application/x-dtbresource+xml res -application/x-dvi dvi -application/x-envoy evy -application/x-eva eva -application/x-font-bdf bdf -# application/x-font-dos -# application/x-font-framemaker -application/x-font-ghostscript gsf -# application/x-font-libgrx -application/x-font-linux-psf psf -application/x-font-otf otf -application/x-font-pcf pcf -application/x-font-snf snf -# application/x-font-speedo -# application/x-font-sunos-news -application/x-font-ttf ttf ttc -application/x-font-type1 pfa pfb pfm afm -application/font-woff woff -# application/x-font-vfont -application/x-freearc arc -application/x-futuresplash spl -application/x-gca-compressed gca -application/x-glulx ulx -application/x-gnumeric gnumeric -application/x-gramps-xml gramps -application/x-gtar gtar -# application/x-gzip -application/x-hdf hdf -application/x-install-instructions install -application/x-iso9660-image iso -application/x-java-jnlp-file jnlp -application/x-latex latex -application/x-lzh-compressed lzh lha -application/x-mie mie -application/x-mobipocket-ebook prc mobi -application/x-ms-application application -application/x-ms-shortcut lnk -application/x-ms-wmd wmd -application/x-ms-wmz wmz -application/x-ms-xbap xbap -application/x-msaccess mdb -application/x-msbinder obd -application/x-mscardfile crd -application/x-msclip clp -application/x-msdownload exe dll com bat msi -application/x-msmediaview mvb m13 m14 -application/x-msmetafile wmf wmz emf emz -application/x-msmoney mny -application/x-mspublisher pub -application/x-msschedule scd -application/x-msterminal trm -application/x-mswrite wri -application/x-netcdf nc cdf -application/x-nzb nzb -application/x-pkcs12 p12 pfx -application/x-pkcs7-certificates p7b spc -application/x-pkcs7-certreqresp p7r -application/x-rar-compressed rar -application/x-research-info-systems ris -application/x-sh sh -application/x-shar shar -application/x-shockwave-flash swf -application/x-silverlight-app xap -application/x-sql sql -application/x-stuffit sit -application/x-stuffitx sitx -application/x-subrip srt -application/x-sv4cpio sv4cpio -application/x-sv4crc sv4crc -application/x-t3vm-image t3 -application/x-tads gam -application/x-tar tar -application/x-tcl tcl -application/x-tex tex -application/x-tex-tfm tfm -application/x-texinfo texinfo texi -application/x-tgif obj -application/x-ustar ustar -application/x-wais-source src -application/x-x509-ca-cert der crt -application/x-xfig fig -application/x-xliff+xml xlf -application/x-xpinstall xpi -application/x-xz xz -application/x-zmachine z1 z2 z3 z4 z5 z6 z7 z8 -# application/x400-bp -application/xaml+xml xaml -# application/xcap-att+xml -# application/xcap-caps+xml -application/xcap-diff+xml xdf -# application/xcap-el+xml -# application/xcap-error+xml -# application/xcap-ns+xml -# application/xcon-conference-info-diff+xml -# application/xcon-conference-info+xml -application/xenc+xml xenc -application/xhtml+xml xhtml xht -# application/xhtml-voice+xml -application/xml xml xsl -application/xml-dtd dtd -# application/xml-external-parsed-entity -# application/xmpp+xml -application/xop+xml xop -application/xproc+xml xpl -application/xslt+xml xslt -application/xspf+xml xspf -application/xv+xml mxml xhvml xvml xvm -application/yang yang -application/yin+xml yin -application/zip zip -# audio/1d-interleaved-parityfec -# audio/32kadpcm -# audio/3gpp -# audio/3gpp2 -# audio/ac3 -audio/adpcm adp -# audio/amr -# audio/amr-wb -# audio/amr-wb+ -# audio/asc -# audio/atrac-advanced-lossless -# audio/atrac-x -# audio/atrac3 -audio/basic au snd -# audio/bv16 -# audio/bv32 -# audio/clearmode -# audio/cn -# audio/dat12 -# audio/dls -# audio/dsr-es201108 -# audio/dsr-es202050 -# audio/dsr-es202211 -# audio/dsr-es202212 -# audio/dv -# audio/dvi4 -# audio/eac3 -# audio/evrc -# audio/evrc-qcp -# audio/evrc0 -# audio/evrc1 -# audio/evrcb -# audio/evrcb0 -# audio/evrcb1 -# audio/evrcwb -# audio/evrcwb0 -# audio/evrcwb1 -# audio/example -# audio/fwdred -# audio/g719 -# audio/g722 -# audio/g7221 -# audio/g723 -# audio/g726-16 -# audio/g726-24 -# audio/g726-32 -# audio/g726-40 -# audio/g728 -# audio/g729 -# audio/g7291 -# audio/g729d -# audio/g729e -# audio/gsm -# audio/gsm-efr -# audio/gsm-hr-08 -# audio/ilbc -# audio/ip-mr_v2.5 -# audio/isac -# audio/l16 -# audio/l20 -# audio/l24 -# audio/l8 -# audio/lpc -audio/midi mid midi kar rmi -# audio/mobile-xmf -audio/mp4 mp4a -# audio/mp4a-latm -# audio/mpa -# audio/mpa-robust -audio/mpeg mpga mp2 mp2a mp3 m2a m3a -# audio/mpeg4-generic -# audio/musepack -audio/ogg oga ogg spx -# audio/opus -# audio/parityfec -# audio/pcma -# audio/pcma-wb -# audio/pcmu-wb -# audio/pcmu -# audio/prs.sid -# audio/qcelp -# audio/red -# audio/rtp-enc-aescm128 -# audio/rtp-midi -# audio/rtx -audio/s3m s3m -audio/silk sil -# audio/smv -# audio/smv0 -# audio/smv-qcp -# audio/sp-midi -# audio/speex -# audio/t140c -# audio/t38 -# audio/telephone-event -# audio/tone -# audio/uemclip -# audio/ulpfec -# audio/vdvi -# audio/vmr-wb -# audio/vnd.3gpp.iufp -# audio/vnd.4sb -# audio/vnd.audiokoz -# audio/vnd.celp -# audio/vnd.cisco.nse -# audio/vnd.cmles.radio-events -# audio/vnd.cns.anp1 -# audio/vnd.cns.inf1 -audio/vnd.dece.audio uva uvva -audio/vnd.digital-winds eol -# audio/vnd.dlna.adts -# audio/vnd.dolby.heaac.1 -# audio/vnd.dolby.heaac.2 -# audio/vnd.dolby.mlp -# audio/vnd.dolby.mps -# audio/vnd.dolby.pl2 -# audio/vnd.dolby.pl2x -# audio/vnd.dolby.pl2z -# audio/vnd.dolby.pulse.1 -audio/vnd.dra dra -audio/vnd.dts dts -audio/vnd.dts.hd dtshd -# audio/vnd.dvb.file -# audio/vnd.everad.plj -# audio/vnd.hns.audio -audio/vnd.lucent.voice lvp -audio/vnd.ms-playready.media.pya pya -# audio/vnd.nokia.mobile-xmf -# audio/vnd.nortel.vbk -audio/vnd.nuera.ecelp4800 ecelp4800 -audio/vnd.nuera.ecelp7470 ecelp7470 -audio/vnd.nuera.ecelp9600 ecelp9600 -# audio/vnd.octel.sbc -# audio/vnd.qcelp -# audio/vnd.rhetorex.32kadpcm -audio/vnd.rip rip -# audio/vnd.sealedmedia.softseal.mpeg -# audio/vnd.vmx.cvsd -# audio/vorbis -# audio/vorbis-config -audio/webm weba -audio/x-aac aac -audio/x-aiff aif aiff aifc -audio/x-caf caf -audio/x-flac flac -audio/x-matroska mka -audio/x-mpegurl m3u -audio/x-ms-wax wax -audio/x-ms-wma wma -audio/x-pn-realaudio ram ra -audio/x-pn-realaudio-plugin rmp -# audio/x-tta -audio/x-wav wav -audio/xm xm -chemical/x-cdx cdx -chemical/x-cif cif -chemical/x-cmdf cmdf -chemical/x-cml cml -chemical/x-csml csml -# chemical/x-pdb -chemical/x-xyz xyz -image/bmp bmp -image/cgm cgm -# image/example -# image/fits -image/g3fax g3 -image/gif gif -image/ief ief -# image/jp2 -image/jpeg jpeg jpg jpe -# image/jpm -# image/jpx -image/ktx ktx -# image/naplps -image/png png -image/prs.btif btif -# image/prs.pti -image/sgi sgi -image/svg+xml svg svgz -# image/t38 -image/tiff tiff tif -# image/tiff-fx -image/vnd.adobe.photoshop psd -# image/vnd.cns.inf2 -image/vnd.dece.graphic uvi uvvi uvg uvvg -image/vnd.dvb.subtitle sub -image/vnd.djvu djvu djv -image/vnd.dwg dwg -image/vnd.dxf dxf -image/vnd.fastbidsheet fbs -image/vnd.fpx fpx -image/vnd.fst fst -image/vnd.fujixerox.edmics-mmr mmr -image/vnd.fujixerox.edmics-rlc rlc -# image/vnd.globalgraphics.pgb -# image/vnd.microsoft.icon -# image/vnd.mix -image/vnd.ms-modi mdi -image/vnd.ms-photo wdp -image/vnd.net-fpx npx -# image/vnd.radiance -# image/vnd.sealed.png -# image/vnd.sealedmedia.softseal.gif -# image/vnd.sealedmedia.softseal.jpg -# image/vnd.svf -image/vnd.wap.wbmp wbmp -image/vnd.xiff xif -image/webp webp -image/x-3ds 3ds -image/x-cmu-raster ras -image/x-cmx cmx -image/x-freehand fh fhc fh4 fh5 fh7 -image/x-icon ico -image/x-mrsid-image sid -image/x-pcx pcx -image/x-pict pic pct -image/x-portable-anymap pnm -image/x-portable-bitmap pbm -image/x-portable-graymap pgm -image/x-portable-pixmap ppm -image/x-rgb rgb -image/x-tga tga -image/x-xbitmap xbm -image/x-xpixmap xpm -image/x-xwindowdump xwd -# message/cpim -# message/delivery-status -# message/disposition-notification -# message/example -# message/external-body -# message/feedback-report -# message/global -# message/global-delivery-status -# message/global-disposition-notification -# message/global-headers -# message/http -# message/imdn+xml -# message/news -# message/partial -message/rfc822 eml mime -# message/s-http -# message/sip -# message/sipfrag -# message/tracking-status -# message/vnd.si.simp -# model/example -model/iges igs iges -model/mesh msh mesh silo -model/vnd.collada+xml dae -model/vnd.dwf dwf -# model/vnd.flatland.3dml -model/vnd.gdl gdl -# model/vnd.gs-gdl -# model/vnd.gs.gdl -model/vnd.gtw gtw -# model/vnd.moml+xml -model/vnd.mts mts -# model/vnd.parasolid.transmit.binary -# model/vnd.parasolid.transmit.text -model/vnd.vtu vtu -model/vrml wrl vrml -model/x3d+binary x3db x3dbz -model/x3d+vrml x3dv x3dvz -model/x3d+xml x3d x3dz -# multipart/alternative -# multipart/appledouble -# multipart/byteranges -# multipart/digest -# multipart/encrypted -# multipart/example -# multipart/form-data -# multipart/header-set -# multipart/mixed -# multipart/parallel -# multipart/related -# multipart/report -# multipart/signed -# multipart/voice-message -# text/1d-interleaved-parityfec -text/cache-manifest appcache -text/calendar ics ifb -text/css css -text/csv csv -# text/directory -# text/dns -# text/ecmascript -# text/enriched -# text/example -# text/fwdred -text/html html htm -# text/javascript -text/n3 n3 -# text/parityfec -text/plain txt text conf def list log in -# text/prs.fallenstein.rst -text/prs.lines.tag dsc -# text/vnd.radisys.msml-basic-layout -# text/red -# text/rfc822-headers -text/richtext rtx -# text/rtf -# text/rtp-enc-aescm128 -# text/rtx -text/sgml sgml sgm -# text/t140 -text/tab-separated-values tsv -text/troff t tr roff man me ms -text/turtle ttl -# text/ulpfec -text/uri-list uri uris urls -text/vcard vcard -# text/vnd.abc -text/vnd.curl curl -text/vnd.curl.dcurl dcurl -text/vnd.curl.scurl scurl -text/vnd.curl.mcurl mcurl -# text/vnd.dmclientscript -text/vnd.dvb.subtitle sub -# text/vnd.esmertec.theme-descriptor -text/vnd.fly fly -text/vnd.fmi.flexstor flx -text/vnd.graphviz gv -text/vnd.in3d.3dml 3dml -text/vnd.in3d.spot spot -# text/vnd.iptc.newsml -# text/vnd.iptc.nitf -# text/vnd.latex-z -# text/vnd.motorola.reflex -# text/vnd.ms-mediapackage -# text/vnd.net2phone.commcenter.command -# text/vnd.si.uricatalogue -text/vnd.sun.j2me.app-descriptor jad -# text/vnd.trolltech.linguist -# text/vnd.wap.si -# text/vnd.wap.sl -text/vnd.wap.wml wml -text/vnd.wap.wmlscript wmls -text/x-asm s asm -text/x-c c cc cxx cpp h hh dic -text/x-fortran f for f77 f90 -text/x-java-source java -text/x-opml opml -text/x-pascal p pas -text/x-nfo nfo -text/x-setext etx -text/x-sfv sfv -text/x-uuencode uu -text/x-vcalendar vcs -text/x-vcard vcf -# text/xml -# text/xml-external-parsed-entity -# video/1d-interleaved-parityfec -video/3gpp 3gp -# video/3gpp-tt -video/3gpp2 3g2 -# video/bmpeg -# video/bt656 -# video/celb -# video/dv -# video/example -video/h261 h261 -video/h263 h263 -# video/h263-1998 -# video/h263-2000 -video/h264 h264 -# video/h264-rcdo -# video/h264-svc -video/jpeg jpgv -# video/jpeg2000 -video/jpm jpm jpgm -video/mj2 mj2 mjp2 -# video/mp1s -# video/mp2p -# video/mp2t -video/mp4 mp4 mp4v mpg4 -# video/mp4v-es -video/mpeg mpeg mpg mpe m1v m2v -# video/mpeg4-generic -# video/mpv -# video/nv -video/ogg ogv -# video/parityfec -# video/pointer -video/quicktime qt mov -# video/raw -# video/rtp-enc-aescm128 -# video/rtx -# video/smpte292m -# video/ulpfec -# video/vc1 -# video/vnd.cctv -video/vnd.dece.hd uvh uvvh -video/vnd.dece.mobile uvm uvvm -# video/vnd.dece.mp4 -video/vnd.dece.pd uvp uvvp -video/vnd.dece.sd uvs uvvs -video/vnd.dece.video uvv uvvv -# video/vnd.directv.mpeg -# video/vnd.directv.mpeg-tts -# video/vnd.dlna.mpeg-tts -video/vnd.dvb.file dvb -video/vnd.fvt fvt -# video/vnd.hns.video -# video/vnd.iptvforum.1dparityfec-1010 -# video/vnd.iptvforum.1dparityfec-2005 -# video/vnd.iptvforum.2dparityfec-1010 -# video/vnd.iptvforum.2dparityfec-2005 -# video/vnd.iptvforum.ttsavc -# video/vnd.iptvforum.ttsmpeg2 -# video/vnd.motorola.video -# video/vnd.motorola.videop -video/vnd.mpegurl mxu m4u -video/vnd.ms-playready.media.pyv pyv -# video/vnd.nokia.interleaved-multimedia -# video/vnd.nokia.videovoip -# video/vnd.objectvideo -# video/vnd.sealed.mpeg1 -# video/vnd.sealed.mpeg4 -# video/vnd.sealed.swf -# video/vnd.sealedmedia.softseal.mov -video/vnd.uvvu.mp4 uvu uvvu -video/vnd.vivo viv -video/webm webm -video/x-f4v f4v -video/x-fli fli -video/x-flv flv -video/x-m4v m4v -video/x-matroska mkv mk3d mks -video/x-mng mng -video/x-ms-asf asf asx -video/x-ms-vob vob -video/x-ms-wm wm -video/x-ms-wmv wmv -video/x-ms-wmx wmx -video/x-ms-wvx wvx -video/x-msvideo avi -video/x-sgi-movie movie -video/x-smv smv -x-conference/x-cooltalk ice diff --git a/server/node_modules/express/node_modules/send/node_modules/mime/types/node.types b/server/node_modules/express/node_modules/send/node_modules/mime/types/node.types deleted file mode 100755 index 55b2cf79..00000000 --- a/server/node_modules/express/node_modules/send/node_modules/mime/types/node.types +++ /dev/null @@ -1,77 +0,0 @@ -# What: WebVTT -# Why: To allow formats intended for marking up external text track resources. -# http://dev.w3.org/html5/webvtt/ -# Added by: niftylettuce -text/vtt vtt - -# What: Google Chrome Extension -# Why: To allow apps to (work) be served with the right content type header. -# http://codereview.chromium.org/2830017 -# Added by: niftylettuce -application/x-chrome-extension crx - -# What: HTC support -# Why: To properly render .htc files such as CSS3PIE -# Added by: niftylettuce -text/x-component htc - -# What: HTML5 application cache manifes ('.manifest' extension) -# Why: De-facto standard. Required by Mozilla browser when serving HTML5 apps -# per https://developer.mozilla.org/en/offline_resources_in_firefox -# Added by: louisremi -text/cache-manifest manifest - -# What: node binary buffer format -# Why: semi-standard extension w/in the node community -# Added by: tootallnate -application/octet-stream buffer - -# What: The "protected" MP-4 formats used by iTunes. -# Why: Required for streaming music to browsers (?) -# Added by: broofa -application/mp4 m4p -audio/mp4 m4a - -# What: Video format, Part of RFC1890 -# Why: See https://github.com/bentomas/node-mime/pull/6 -# Added by: mjrusso -video/MP2T ts - -# What: EventSource mime type -# Why: mime type of Server-Sent Events stream -# http://www.w3.org/TR/eventsource/#text-event-stream -# Added by: francois2metz -text/event-stream event-stream - -# What: Mozilla App manifest mime type -# Why: https://developer.mozilla.org/en/Apps/Manifest#Serving_manifests -# Added by: ednapiranha -application/x-web-app-manifest+json webapp - -# What: Lua file types -# Why: Googling around shows de-facto consensus on these -# Added by: creationix (Issue #45) -text/x-lua lua -application/x-lua-bytecode luac - -# What: Markdown files, as per http://daringfireball.net/projects/markdown/syntax -# Why: http://stackoverflow.com/questions/10701983/what-is-the-mime-type-for-markdown -# Added by: avoidwork -text/x-markdown markdown md mkd - -# What: ini files -# Why: because they're just text files -# Added by: Matthew Kastor -text/plain ini - -# What: DASH Adaptive Streaming manifest -# Why: https://developer.mozilla.org/en-US/docs/DASH_Adaptive_Streaming_for_HTML_5_Video -# Added by: eelcocramer -application/dash+xml mdp - -# What: OpenType font files - http://www.microsoft.com/typography/otspec/ -# Why: Browsers usually ignore the font MIME types and sniff the content, -# but Chrome, shows a warning if OpenType fonts aren't served with -# the `font/opentype` MIME type: http://i.imgur.com/8c5RN8M.png. -# Added by: alrra -font/opentype otf diff --git a/server/node_modules/express/node_modules/send/node_modules/ms/.npmignore b/server/node_modules/express/node_modules/send/node_modules/ms/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/send/node_modules/ms/README.md b/server/node_modules/express/node_modules/send/node_modules/ms/README.md old mode 100755 new mode 100644 index d4ab12a7..9b4fd035 --- a/server/node_modules/express/node_modules/send/node_modules/ms/README.md +++ b/server/node_modules/express/node_modules/send/node_modules/ms/README.md @@ -1,8 +1,10 @@ # ms.js: miliseconds conversion utility ```js +ms('2 days') // 172800000 ms('1d') // 86400000 ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 ms('2h') // 7200000 ms('1m') // 60000 ms('5s') // 5000 @@ -18,10 +20,10 @@ ms(ms('10 hours')) // "10h" ```js ms(60000, { long: true }) // "1 minute" ms(2 * 60000, { long: true }) // "2 minutes" -ms(ms('10 hours', { long: true })) // "10 hours" +ms(ms('10 hours'), { long: true }) // "10 hours" ``` -- Node/Browser compatible. Published as `ms` in NPM. +- Node/Browser compatible. Published as [`ms`](https://www.npmjs.org/package/ms) in [NPM](http://nodejs.org/download). - If a number is supplied to `ms`, a string with a unit is returned. - If a string that contains the number is supplied, it returns it as a number (e.g: it returns `100` for `'100'`). @@ -30,4 +32,4 @@ equivalent ms is returned. ## License -MIT \ No newline at end of file +MIT diff --git a/server/node_modules/express/node_modules/send/node_modules/ms/index.js b/server/node_modules/express/node_modules/send/node_modules/ms/index.js old mode 100755 new mode 100644 index c5847f8d..4f927716 --- a/server/node_modules/express/node_modules/send/node_modules/ms/index.js +++ b/server/node_modules/express/node_modules/send/node_modules/ms/index.js @@ -38,13 +38,17 @@ module.exports = function(val, options){ */ function parse(str) { - var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); + str = '' + str; + if (str.length > 10000) return; + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); if (!match) return; var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': + case 'yrs': + case 'yr': case 'y': return n * y; case 'days': @@ -53,16 +57,26 @@ function parse(str) { return n * d; case 'hours': case 'hour': + case 'hrs': + case 'hr': case 'h': return n * h; case 'minutes': case 'minute': + case 'mins': + case 'min': case 'm': return n * m; case 'seconds': case 'second': + case 'secs': + case 'sec': case 's': return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': case 'ms': return n; } diff --git a/server/node_modules/express/node_modules/send/node_modules/ms/package.json b/server/node_modules/express/node_modules/send/node_modules/ms/package.json old mode 100755 new mode 100644 index 83344111..a273574f --- a/server/node_modules/express/node_modules/send/node_modules/ms/package.json +++ b/server/node_modules/express/node_modules/send/node_modules/ms/package.json @@ -1,6 +1,6 @@ { "name": "ms", - "version": "0.6.2", + "version": "0.7.1", "description": "Tiny ms conversion utility", "repository": { "type": "git", @@ -17,27 +17,15 @@ "ms/index.js": "index.js" } }, + "readme": "# ms.js: miliseconds conversion utility\n\n```js\nms('2 days') // 172800000\nms('1d') // 86400000\nms('10h') // 36000000\nms('2.5 hrs') // 9000000\nms('2h') // 7200000\nms('1m') // 60000\nms('5s') // 5000\nms('100') // 100\n```\n\n```js\nms(60000) // \"1m\"\nms(2 * 60000) // \"2m\"\nms(ms('10 hours')) // \"10h\"\n```\n\n```js\nms(60000, { long: true }) // \"1 minute\"\nms(2 * 60000, { long: true }) // \"2 minutes\"\nms(ms('10 hours'), { long: true }) // \"10 hours\"\n```\n\n- Node/Browser compatible. Published as [`ms`](https://www.npmjs.org/package/ms) in [NPM](http://nodejs.org/download).\n- If a number is supplied to `ms`, a string with a unit is returned.\n- If a string that contains the number is supplied, it returns it as\na number (e.g: it returns `100` for `'100'`).\n- If you pass a string with a number and a valid unit, the number of\nequivalent ms is returned.\n\n## License\n\nMIT\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/guille/ms.js/issues" }, - "_id": "ms@0.6.2", + "_id": "ms@0.7.1", "dist": { - "shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", - "tarball": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz" + "shasum": "71c4b4174f5b6aa0101eb56e733ee5f6b4c1a917" }, - "_from": "ms@0.6.2", - "_npmVersion": "1.2.30", - "_npmUser": { - "name": "rauchg", - "email": "rauchg@gmail.com" - }, - "maintainers": [ - { - "name": "rauchg", - "email": "rauchg@gmail.com" - } - ], - "directories": {}, - "_shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", - "_resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz" + "_from": "ms@0.7.1", + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz" } diff --git a/server/node_modules/express/node_modules/send/package.json b/server/node_modules/express/node_modules/send/package.json old mode 100755 new mode 100644 index de43e7df..bd8f2754 --- a/server/node_modules/express/node_modules/send/package.json +++ b/server/node_modules/express/node_modules/send/package.json @@ -1,7 +1,7 @@ { "name": "send", "description": "Better streaming static file server with Range and conditional-GET support", - "version": "0.10.1", + "version": "0.12.3", "author": { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca" @@ -15,7 +15,7 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/tj/send" + "url": "git://github.com/pillarjs/send" }, "keywords": [ "static", @@ -23,26 +23,27 @@ "server" ], "dependencies": { - "debug": "~2.1.0", - "depd": "~1.0.0", + "debug": "~2.2.0", + "depd": "~1.0.1", "destroy": "1.0.3", "escape-html": "1.0.1", - "etag": "~1.5.0", + "etag": "~1.6.0", "fresh": "0.2.4", - "mime": "1.2.11", - "ms": "0.6.2", - "on-finished": "~2.1.1", + "mime": "1.3.4", + "ms": "0.7.1", + "on-finished": "~2.2.1", "range-parser": "~1.0.2" }, "devDependencies": { - "istanbul": "0.3.2", - "mocha": "~2.0.0", - "should": "~4.1.0", - "supertest": "~0.14.0" + "after": "0.8.1", + "istanbul": "0.3.9", + "mocha": "2.2.4", + "supertest": "~0.15.0" }, "files": [ - "History.md", + "HISTORY.md", "LICENSE", + "README.md", "index.js" ], "engines": { @@ -50,36 +51,18 @@ }, "scripts": { "test": "mocha --check-leaks --reporter spec --bail", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec" + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot" }, - "gitHead": "a5e6237f3e812a99d079e2100f6294251ef5f465", + "readme": "# send\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Linux Build][travis-image]][travis-url]\n[![Windows Build][appveyor-image]][appveyor-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n[![Gratipay][gratipay-image]][gratipay-url]\n\nSend is a library for streaming files from the file system as a http response\nsupporting partial responses (Ranges), conditional-GET negotiation, high test\ncoverage, and granular events which may be leveraged to take appropriate actions\nin your application or framework.\n\nLooking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static).\n\n## Installation\n\n```bash\n$ npm install send\n```\n\n## API\n\n```js\nvar send = require('send')\n```\n\n### send(req, path, [options])\n\nCreate a new `SendStream` for the given path to send to a `res`. The `req` is\nthe Node.js HTTP request and the `path` is a urlencoded path to send (urlencoded,\nnot the actual file-system path).\n\n#### Options\n\n##### dotfiles\n\nSet how \"dotfiles\" are treated when encountered. A dotfile is a file\nor directory that begins with a dot (\".\"). Note this check is done on\nthe path itself without checking if the path actually exists on the\ndisk. If `root` is specified, only the dotfiles above the root are\nchecked (i.e. the root itself can be within a dotfile when when set\nto \"deny\").\n\n - `'allow'` No special treatment for dotfiles.\n - `'deny'` Send a 403 for any request for a dotfile.\n - `'ignore'` Pretend like the dotfile does not exist and 404.\n\nThe default value is _similar_ to `'ignore'`, with the exception that\nthis default will not ignore the files within a directory that begins\nwith a dot, for backward-compatibility.\n\n##### etag\n\nEnable or disable etag generation, defaults to true.\n\n##### extensions\n\nIf a given file doesn't exist, try appending one of the given extensions,\nin the given order. By default, this is disabled (set to `false`). An\nexample value that will serve extension-less HTML files: `['html', 'htm']`.\nThis is skipped if the requested file already has an extension.\n\n##### index\n\nBy default send supports \"index.html\" files, to disable this\nset `false` or to supply a new index pass a string or an array\nin preferred order.\n\n##### lastModified\n\nEnable or disable `Last-Modified` header, defaults to true. Uses the file\nsystem's last modified value.\n\n##### maxAge\n\nProvide a max-age in milliseconds for http caching, defaults to 0.\nThis can also be a string accepted by the\n[ms](https://www.npmjs.org/package/ms#readme) module.\n\n##### root\n\nServe files relative to `path`.\n\n### Events\n\nThe `SendStream` is an event emitter and will emit the following events:\n\n - `error` an error occurred `(err)`\n - `directory` a directory was requested\n - `file` a file was requested `(path, stat)`\n - `headers` the headers are about to be set on a file `(res, path, stat)`\n - `stream` file streaming has started `(stream)`\n - `end` streaming has completed\n\n### .pipe\n\nThe `pipe` method is used to pipe the response into the Node.js HTTP response\nobject, typically `send(req, path, options).pipe(res)`.\n\n## Error-handling\n\nBy default when no `error` listeners are present an automatic response will be\nmade, otherwise you have full control over the response, aka you may show a 5xx\npage etc.\n\n## Caching\n\nIt does _not_ perform internal caching, you should use a reverse proxy cache\nsuch as Varnish for this, or those fancy things called CDNs. If your\napplication is small enough that it would benefit from single-node memory\ncaching, it's small enough that it does not need caching at all ;).\n\n## Debugging\n\nTo enable `debug()` instrumentation output export __DEBUG__:\n\n```\n$ DEBUG=send node app\n```\n\n## Running tests\n\n```\n$ npm install\n$ npm test\n```\n\n## Examples\n\n### Small example\n\n```js\nvar http = require('http');\nvar send = require('send');\n\nvar app = http.createServer(function(req, res){\n send(req, req.url).pipe(res);\n}).listen(3000);\n```\n\nServing from a root directory with custom error-handling:\n\n```js\nvar http = require('http');\nvar send = require('send');\nvar url = require('url');\n\nvar app = http.createServer(function(req, res){\n // your custom error-handling logic:\n function error(err) {\n res.statusCode = err.status || 500;\n res.end(err.message);\n }\n\n // your custom headers\n function headers(res, path, stat) {\n // serve all files for download\n res.setHeader('Content-Disposition', 'attachment');\n }\n\n // your custom directory handling logic:\n function redirect() {\n res.statusCode = 301;\n res.setHeader('Location', req.url + '/');\n res.end('Redirecting to ' + req.url + '/');\n }\n\n // transfer arbitrary files from within\n // /www/example.com/public/*\n send(req, url.parse(req.url).pathname, {root: '/www/example.com/public'})\n .on('error', error)\n .on('directory', redirect)\n .on('headers', headers)\n .pipe(res);\n}).listen(3000);\n```\n\n## License \n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/send.svg\n[npm-url]: https://npmjs.org/package/send\n[travis-image]: https://img.shields.io/travis/pillarjs/send/master.svg?label=linux\n[travis-url]: https://travis-ci.org/pillarjs/send\n[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/send/master.svg?label=windows\n[appveyor-url]: https://ci.appveyor.com/project/dougwilson/send\n[coveralls-image]: https://img.shields.io/coveralls/pillarjs/send/master.svg\n[coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/send.svg\n[downloads-url]: https://npmjs.org/package/send\n[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg\n[gratipay-url]: https://www.gratipay.com/dougwilson/\n", + "readmeFilename": "README.md", "bugs": { - "url": "https://github.com/tj/send/issues" + "url": "https://github.com/pillarjs/send/issues" }, - "homepage": "https://github.com/tj/send", - "_id": "send@0.10.1", - "_shasum": "7745c50ec72f115115980e8fb179aec01900e08a", - "_from": "send@0.10.1", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], + "_id": "send@0.12.3", "dist": { - "shasum": "7745c50ec72f115115980e8fb179aec01900e08a", - "tarball": "http://registry.npmjs.org/send/-/send-0.10.1.tgz" + "shasum": "97f6291c7e917915b8020f5e8fa4345b671034c1" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/send/-/send-0.10.1.tgz" + "_from": "send@0.12.3", + "_resolved": "https://registry.npmjs.org/send/-/send-0.12.3.tgz" } diff --git a/server/node_modules/express/node_modules/serve-static/HISTORY.md b/server/node_modules/express/node_modules/serve-static/HISTORY.md old mode 100755 new mode 100644 index 768d8f2c..581e4f86 --- a/server/node_modules/express/node_modules/serve-static/HISTORY.md +++ b/server/node_modules/express/node_modules/serve-static/HISTORY.md @@ -1,3 +1,50 @@ +1.9.3 / 2015-05-14 +================== + + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +1.9.2 / 2015-03-14 +================== + + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +1.9.1 / 2015-02-17 +================== + + * deps: send@0.12.1 + - Fix regression sending zero-length files + +1.9.0 / 2015-02-16 +================== + + * deps: send@0.12.0 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +1.8.1 / 2015-01-20 +================== + + * Fix redirect loop in Node.js 0.11.14 + * deps: send@0.11.1 + - Fix root path disclosure + +1.8.0 / 2015-01-05 +================== + + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + 1.7.2 / 2015-01-02 ================== @@ -17,6 +64,12 @@ - deps: depd@~1.0.0 - deps: etag@~1.5.0 +1.6.5 / 2015-02-04 +================== + + * Fix potential open redirect when mounted at root + - Back-ported from v1.7.2 + 1.6.4 / 2014-10-08 ================== diff --git a/server/node_modules/express/node_modules/serve-static/LICENSE b/server/node_modules/express/node_modules/serve-static/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/serve-static/README.md b/server/node_modules/express/node_modules/serve-static/README.md old mode 100755 new mode 100644 index 7d952310..125a90c7 --- a/server/node_modules/express/node_modules/serve-static/README.md +++ b/server/node_modules/express/node_modules/serve-static/README.md @@ -2,7 +2,8 @@ [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] -[![Build Status][travis-image]][travis-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] [![Test Coverage][coveralls-image]][coveralls-url] [![Gratipay][gratipay-image]][gratipay-url] @@ -34,7 +35,7 @@ to the next middleware, allowing for stacking and fall-backs. or directory that begins with a dot ("."). Note this check is done on the path itself without checking if the path actually exists on the disk. If `root` is specified, only the dotfiles above the root are -checked (i.e. the root itself can be within a dotfile when when set +checked (i.e. the root itself can be within a dotfile when set to "deny"). The default value is `'ignore'`. @@ -139,27 +140,77 @@ server.listen(3000) ### Serving using express +#### Simple + +This is a simple example of using Express. + ```js -var connect = require('connect') +var express = require('express') var serveStatic = require('serve-static') -var app = connect() +var app = express() app.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']})) app.listen(3000) ``` +#### Multiple roots + +This example shows a simple way to search through multiple directories. +Files are look for in `public-optimized/` first, then `public/` second as +a fallback. + +```js +var express = require('express') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic(__dirname + '/public-optimized')) +app.use(serveStatic(__dirname + '/public')) +app.listen(3000) +``` + +#### Different settings for paths + +This example shows how to set a different max age depending on the served +file type. In this example, HTML files are not cached, while everything else +is for 1 day. + +```js +var express = require('express') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic(__dirname + '/public', { + maxAge: '1d', + setHeaders: setCustomCacheControl +})) + +app.listen(3000) + +function setCustomCacheControl(res, path) { + if (serveStatic.mime.lookup(path) === 'text/html') { + // Custom Cache-Control for HTML files + res.setHeader('Cache-Control', 'public, max-age=0') + } +} +``` + ## License [MIT](LICENSE) -[npm-image]: https://img.shields.io/npm/v/serve-static.svg?style=flat +[npm-image]: https://img.shields.io/npm/v/serve-static.svg [npm-url]: https://npmjs.org/package/serve-static -[travis-image]: https://img.shields.io/travis/expressjs/serve-static.svg?style=flat +[travis-image]: https://img.shields.io/travis/expressjs/serve-static/master.svg?label=linux [travis-url]: https://travis-ci.org/expressjs/serve-static -[coveralls-image]: https://img.shields.io/coveralls/expressjs/serve-static.svg?style=flat +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/serve-static/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-static +[coveralls-image]: https://img.shields.io/coveralls/expressjs/serve-static/master.svg [coveralls-url]: https://coveralls.io/r/expressjs/serve-static -[downloads-image]: https://img.shields.io/npm/dm/serve-static.svg?style=flat +[downloads-image]: https://img.shields.io/npm/dm/serve-static.svg [downloads-url]: https://npmjs.org/package/serve-static -[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg?style=flat +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg [gratipay-url]: https://gratipay.com/dougwilson/ diff --git a/server/node_modules/express/node_modules/serve-static/index.js b/server/node_modules/express/node_modules/serve-static/index.js old mode 100755 new mode 100644 index fbe044cf..0d1d9fbc --- a/server/node_modules/express/node_modules/serve-static/index.js +++ b/server/node_modules/express/node_modules/serve-static/index.js @@ -80,6 +80,7 @@ exports = module.exports = function serveStatic(root, options) { } // append trailing slash + originalUrl.path = null originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') // reformat the URL diff --git a/server/node_modules/express/node_modules/serve-static/package.json b/server/node_modules/express/node_modules/serve-static/package.json old mode 100755 new mode 100644 index ec2aabcb..20bce3ac --- a/server/node_modules/express/node_modules/serve-static/package.json +++ b/server/node_modules/express/node_modules/serve-static/package.json @@ -1,7 +1,7 @@ { "name": "serve-static", "description": "Serve static files", - "version": "1.7.2", + "version": "1.9.3", "author": { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" @@ -9,18 +9,18 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/expressjs/serve-static" + "url": "git://github.com/expressjs/serve-static" }, "dependencies": { "escape-html": "1.0.1", "parseurl": "~1.3.0", - "send": "0.10.1", + "send": "0.12.3", "utils-merge": "1.0.0" }, "devDependencies": { - "istanbul": "0.3.5", - "mocha": "~2.1.0", - "supertest": "~0.15.0" + "istanbul": "0.3.9", + "mocha": "2.2.5", + "supertest": "1.0.1" }, "files": [ "LICENSE", @@ -32,52 +32,14 @@ }, "scripts": { "test": "mocha --reporter spec --bail --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" }, - "gitHead": "40f88bd0269cd4f4ffcb52bded570ad57e4b56ba", + "readme": "# serve-static\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Linux Build][travis-image]][travis-url]\n[![Windows Build][appveyor-image]][appveyor-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n[![Gratipay][gratipay-image]][gratipay-url]\n\n## Install\n\n```sh\n$ npm install serve-static\n```\n\n## API\n\n```js\nvar serveStatic = require('serve-static')\n```\n\n### serveStatic(root, options)\n\nCreate a new middleware function to serve files from within a given root\ndirectory. The file to serve will be determined by combining `req.url`\nwith the provided root directory. When a file is not found, instead of\nsending a 404 response, this module will instead call `next()` to move on\nto the next middleware, allowing for stacking and fall-backs.\n\n#### Options\n\n##### dotfiles\n\n Set how \"dotfiles\" are treated when encountered. A dotfile is a file\nor directory that begins with a dot (\".\"). Note this check is done on\nthe path itself without checking if the path actually exists on the\ndisk. If `root` is specified, only the dotfiles above the root are\nchecked (i.e. the root itself can be within a dotfile when set\nto \"deny\").\n\nThe default value is `'ignore'`.\n\n - `'allow'` No special treatment for dotfiles.\n - `'deny'` Send a 403 for any request for a dotfile.\n - `'ignore'` Pretend like the dotfile does not exist and call `next()`.\n\n##### etag\n\nEnable or disable etag generation, defaults to true.\n\n##### extensions\n\nSet file extension fallbacks. When set, if a file is not found, the given\nextensions will be added to the file name and search for. The first that\nexists will be served. Example: `['html', 'htm']`.\n\nThe default value is `false`.\n\n##### index\n\nBy default this module will send \"index.html\" files in response to a request\non a directory. To disable this set `false` or to supply a new index pass a\nstring or an array in preferred order.\n\n##### lastModified\n\nEnable or disable `Last-Modified` header, defaults to true. Uses the file\nsystem's last modified value.\n\n##### maxAge\n\nProvide a max-age in milliseconds for http caching, defaults to 0. This\ncan also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme)\nmodule.\n\n##### redirect\n\nRedirect to trailing \"/\" when the pathname is a dir. Defaults to `true`.\n\n##### setHeaders\n\nFunction to set custom headers on response. Alterations to the headers need to\noccur synchronously. The function is called as `fn(res, path, stat)`, where\nthe arguments are:\n\n - `res` the response object\n - `path` the file path that is being sent\n - `stat` the stat object of the file that is being sent\n\n## Examples\n\n### Serve files with vanilla node.js http server\n\n```js\nvar finalhandler = require('finalhandler')\nvar http = require('http')\nvar serveStatic = require('serve-static')\n\n// Serve up public/ftp folder\nvar serve = serveStatic('public/ftp', {'index': ['index.html', 'index.htm']})\n\n// Create server\nvar server = http.createServer(function(req, res){\n var done = finalhandler(req, res)\n serve(req, res, done)\n})\n\n// Listen\nserver.listen(3000)\n```\n\n### Serve all files as downloads\n\n```js\nvar contentDisposition = require('content-disposition')\nvar finalhandler = require('finalhandler')\nvar http = require('http')\nvar serveStatic = require('serve-static')\n\n// Serve up public/ftp folder\nvar serve = serveStatic('public/ftp', {\n 'index': false,\n 'setHeaders': setHeaders\n})\n\n// Set header to force download\nfunction setHeaders(res, path) {\n res.setHeader('Content-Disposition', contentDisposition(path))\n}\n\n// Create server\nvar server = http.createServer(function(req, res){\n var done = finalhandler(req, res)\n serve(req, res, done)\n})\n\n// Listen\nserver.listen(3000)\n```\n\n### Serving using express\n\n#### Simple\n\nThis is a simple example of using Express.\n\n```js\nvar express = require('express')\nvar serveStatic = require('serve-static')\n\nvar app = express()\n\napp.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']}))\napp.listen(3000)\n```\n\n#### Multiple roots\n\nThis example shows a simple way to search through multiple directories.\nFiles are look for in `public-optimized/` first, then `public/` second as\na fallback.\n\n```js\nvar express = require('express')\nvar serveStatic = require('serve-static')\n\nvar app = express()\n\napp.use(serveStatic(__dirname + '/public-optimized'))\napp.use(serveStatic(__dirname + '/public'))\napp.listen(3000)\n```\n\n#### Different settings for paths\n\nThis example shows how to set a different max age depending on the served\nfile type. In this example, HTML files are not cached, while everything else\nis for 1 day.\n\n```js\nvar express = require('express')\nvar serveStatic = require('serve-static')\n\nvar app = express()\n\napp.use(serveStatic(__dirname + '/public', {\n maxAge: '1d',\n setHeaders: setCustomCacheControl\n}))\n\napp.listen(3000)\n\nfunction setCustomCacheControl(res, path) {\n if (serveStatic.mime.lookup(path) === 'text/html') {\n // Custom Cache-Control for HTML files\n res.setHeader('Cache-Control', 'public, max-age=0')\n }\n}\n```\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/serve-static.svg\n[npm-url]: https://npmjs.org/package/serve-static\n[travis-image]: https://img.shields.io/travis/expressjs/serve-static/master.svg?label=linux\n[travis-url]: https://travis-ci.org/expressjs/serve-static\n[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/serve-static/master.svg?label=windows\n[appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-static\n[coveralls-image]: https://img.shields.io/coveralls/expressjs/serve-static/master.svg\n[coveralls-url]: https://coveralls.io/r/expressjs/serve-static\n[downloads-image]: https://img.shields.io/npm/dm/serve-static.svg\n[downloads-url]: https://npmjs.org/package/serve-static\n[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg\n[gratipay-url]: https://gratipay.com/dougwilson/\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/expressjs/serve-static/issues" }, - "homepage": "https://github.com/expressjs/serve-static", - "_id": "serve-static@1.7.2", - "_shasum": "3164ce06d4e6c3459bdcc9d6018fb4fb35e84b39", - "_from": "serve-static@~1.7.1", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "shtylman", - "email": "shtylman@gmail.com" - }, - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "mscdex", - "email": "mscdex@mscdex.net" - }, - { - "name": "fishrock123", - "email": "fishrock123@rocketmail.com" - } - ], - "dist": { - "shasum": "3164ce06d4e6c3459bdcc9d6018fb4fb35e84b39", - "tarball": "http://registry.npmjs.org/serve-static/-/serve-static-1.7.2.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.7.2.tgz" + "_id": "serve-static@1.9.3", + "_from": "serve-static@~1.9.3" } diff --git a/server/node_modules/express/node_modules/type-is/HISTORY.md b/server/node_modules/express/node_modules/type-is/HISTORY.md old mode 100755 new mode 100644 index e3cab75a..3687bf9f --- a/server/node_modules/express/node_modules/type-is/HISTORY.md +++ b/server/node_modules/express/node_modules/type-is/HISTORY.md @@ -1,3 +1,29 @@ +1.6.3 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - Add new mime types + * perf: reduce try block size + * perf: remove bitwise operations + +1.6.2 / 2015-05-10 +================== + + * deps: mime-types@~2.0.11 + - Add new mime types + +1.6.1 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - Add new mime types + +1.6.0 / 2015-02-12 +================== + + * fix false-positives in `hasBody` `Transfer-Encoding` check + * support wildcard for both type and subtype (`*/*`) + 1.5.7 / 2015-02-09 ================== diff --git a/server/node_modules/express/node_modules/type-is/LICENSE b/server/node_modules/express/node_modules/type-is/LICENSE old mode 100755 new mode 100644 index 4164d08a..386b7b69 --- a/server/node_modules/express/node_modules/type-is/LICENSE +++ b/server/node_modules/express/node_modules/type-is/LICENSE @@ -1,21 +1,23 @@ -The MIT License (MIT) +(The MIT License) -Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +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 above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/express/node_modules/type-is/README.md b/server/node_modules/express/node_modules/type-is/README.md old mode 100755 new mode 100644 index 0beeed81..9b393da7 --- a/server/node_modules/express/node_modules/type-is/README.md +++ b/server/node_modules/express/node_modules/type-is/README.md @@ -60,10 +60,10 @@ is.is(mediaType, ['html']) // false - An extension name such as `json`. This name will be returned if matched. - A mime type such as `application/json`. -- A mime type with a wildcard such as `*/json` or `application/*`. The full mime type will be returned if matched +- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. The full mime type will be returned if matched. - A suffix such as `+json`. This can be combined with a wildcard such as `*/vnd+json` or `application/*+json`. The full mime type will be returned if matched. -`false` will be returned if no type matches. +`false` will be returned if no type matches or the content type is invalid. `null` will be returned if the request does not have a body. @@ -105,13 +105,13 @@ function bodyParser(req, res, next) { [MIT](LICENSE) -[npm-image]: https://img.shields.io/npm/v/type-is.svg?style=flat +[npm-image]: https://img.shields.io/npm/v/type-is.svg [npm-url]: https://npmjs.org/package/type-is -[node-version-image]: https://img.shields.io/node/v/type-is.svg?style=flat +[node-version-image]: https://img.shields.io/node/v/type-is.svg [node-version-url]: http://nodejs.org/download/ -[travis-image]: https://img.shields.io/travis/jshttp/type-is.svg?style=flat +[travis-image]: https://img.shields.io/travis/jshttp/type-is/master.svg [travis-url]: https://travis-ci.org/jshttp/type-is -[coveralls-image]: https://img.shields.io/coveralls/jshttp/type-is.svg?style=flat +[coveralls-image]: https://img.shields.io/coveralls/jshttp/type-is/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master -[downloads-image]: https://img.shields.io/npm/dm/type-is.svg?style=flat +[downloads-image]: https://img.shields.io/npm/dm/type-is.svg [downloads-url]: https://npmjs.org/package/type-is diff --git a/server/node_modules/express/node_modules/type-is/index.js b/server/node_modules/express/node_modules/type-is/index.js old mode 100755 new mode 100644 index 73e885ae..16c9d4ec --- a/server/node_modules/express/node_modules/type-is/index.js +++ b/server/node_modules/express/node_modules/type-is/index.js @@ -1,3 +1,9 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ var typer = require('media-typer') var mime = require('mime-types') @@ -27,7 +33,7 @@ function typeis(value, types_) { var types = types_ // remove parameters and normalize - var val = typenormalize(value) + var val = tryNormalizeType(value) // no type or invalid if (!val) { @@ -50,7 +56,7 @@ function typeis(value, types_) { var type for (i = 0; i < types.length; i++) { if (mimeMatch(normalize(type = types[i]), val)) { - return type[0] === '+' || ~type.indexOf('*') + return type[0] === '+' || type.indexOf('*') !== -1 ? val : type } @@ -72,9 +78,8 @@ function typeis(value, types_) { */ function hasbody(req) { - var headers = req.headers; - if ('transfer-encoding' in headers) return true; - return !isNaN(headers['content-length']); + return req.headers['transfer-encoding'] !== undefined + || !isNaN(req.headers['content-length']) } /** @@ -143,15 +148,22 @@ function typeofrequest(req, types_) { function normalize(type) { switch (type) { - case 'urlencoded': return 'application/x-www-form-urlencoded'; + case 'urlencoded': + type = 'application/x-www-form-urlencoded' + break case 'multipart': - type = 'multipart/*'; - break; + type = 'multipart/*' + break } - return type[0] === '+' || ~type.indexOf('/') - ? type - : mime.lookup(type) + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + type = '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type } /** @@ -171,42 +183,32 @@ function mimeMatch(expected, actual) { return false } - // exact match - if (expected === actual) { - return true + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false } - actual = actual.split('/'); - - if (expected[0] === '+') { - // support +suffix - return Boolean(actual[1]) - && expected.length <= actual[1].length - && expected === actual[1].substr(0 - expected.length) + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false } - if (!~expected.indexOf('*')) return false; - - expected = expected.split('/'); - - if (expected[0] === '*') { - // support */yyy - return expected[1] === actual[1] + // validate suffix wildcard + if (expectedParts[1].substr(0, 2) === '*+') { + return expectedParts[1].length <= actualParts[1].length + 1 + && expectedParts[1].substr(1) === actualParts[1].substr(1 - expectedParts[1].length) } - if (expected[1] === '*') { - // support xxx/* - return expected[0] === actual[0] + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false } - if (expected[1][0] === '*' && expected[1][1] === '+') { - // support xxx/*+zzz - return expected[0] === actual[0] - && expected[1].length <= actual[1].length + 1 - && expected[1].substr(1) === actual[1].substr(1 - expected[1].length) - } - - return false + return true } /** @@ -214,14 +216,31 @@ function mimeMatch(expected, actual) { * * @param {string} value * @return {string} - * @api private + * @private */ -function typenormalize(value) { +function normalizeType(value) { + // parse the type + var type = typer.parse(value) + + // remove the parameters + type.parameters = undefined + + // reformat it + return typer.format(type) +} + +/** + * Try to normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +function tryNormalizeType(value) { try { - var type = typer.parse(value) - delete type.parameters - return typer.format(type) + return normalizeType(value) } catch (err) { return null } diff --git a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md old mode 100755 new mode 100644 index aa7cdf16..54689f91 --- a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md +++ b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md @@ -1,3 +1,47 @@ +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + 2.0.10 / 2015-03-13 =================== diff --git a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE old mode 100755 new mode 100644 index a7ae8ee9..06166077 --- a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE +++ b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE @@ -1,22 +1,23 @@ +(The MIT License) -The MIT License (MIT) +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson -Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: -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 above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md old mode 100755 new mode 100644 index 8fea7ff4..e26295d0 --- a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md +++ b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md @@ -42,10 +42,11 @@ All functions return `false` if input is invalid or not found. Lookup the content-type associated with a file. ```js -mime.lookup('json') // 'application/json' -mime.lookup('.md') // 'text/x-markdown' -mime.lookup('file.html') // 'text/html' -mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false mime.lookup('cats') // false ``` @@ -90,13 +91,13 @@ A map of extensions by content-type. [MIT](LICENSE) -[npm-image]: https://img.shields.io/npm/v/mime-types.svg?style=flat +[npm-image]: https://img.shields.io/npm/v/mime-types.svg [npm-url]: https://npmjs.org/package/mime-types -[node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat +[node-version-image]: https://img.shields.io/node/v/mime-types.svg [node-version-url]: http://nodejs.org/download/ -[travis-image]: https://img.shields.io/travis/jshttp/mime-types.svg?style=flat +[travis-image]: https://img.shields.io/travis/jshttp/mime-types/master.svg [travis-url]: https://travis-ci.org/jshttp/mime-types -[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-types.svg?style=flat +[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-types/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/mime-types -[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg?style=flat +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg [downloads-url]: https://npmjs.org/package/mime-types diff --git a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js old mode 100755 new mode 100644 index b46a202f..9edf72b7 --- a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js +++ b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js @@ -1,63 +1,188 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ var db = require('mime-db') +var extname = require('path').extname -// types[extension] = type -exports.types = Object.create(null) -// extensions[type] = [extensions] +/** + * Module variables. + * @private + */ + +var extractTypeRegExp = /^\s*([^;\s]*)(?:;|\s|$)/ +var textTypeRegExp = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) -Object.keys(db).forEach(function (name) { - var mime = db[name] - var exts = mime.extensions - if (!exts || !exts.length) return - exports.extensions[name] = exts - exts.forEach(function (ext) { - exports.types[ext] = name - }) -}) +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) -exports.lookup = function (string) { - if (!string || typeof string !== "string") return false - // remove any leading paths, though we should just use path.basename - string = string.replace(/.*[\.\/\\]/, '').toLowerCase() - if (!string) return false - return exports.types[string] || false -} +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ -exports.extension = function (type) { - if (!type || typeof type !== "string") return false - // to do: use media-typer - type = type.match(/^\s*([^;\s]*)(?:;|\s|$)/) - if (!type) return false - var exts = exports.extensions[type[1].toLowerCase()] - if (!exts || !exts.length) return false - return exts[0] -} +function charset(type) { + if (!type || typeof type !== 'string') { + return false + } -// type has to be an exact mime type -exports.charset = function (type) { - var mime = db[type] - if (mime && mime.charset) return mime.charset + // TODO: use media-typer + var match = extractTypeRegExp.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } // default text/* to utf-8 - if (/^text\//.test(type)) return 'UTF-8' + if (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } return false } -// backwards compatibility -exports.charsets = { - lookup: exports.charset +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType(str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime } -// to do: maybe use set-type module or something -exports.contentType = function (type) { - if (!type || typeof type !== "string") return false - if (!~type.indexOf('/')) type = exports.lookup(type) - if (!type) return false - if (!~type.indexOf('charset')) { - var charset = exports.charset(type) - if (charset) type += '; charset=' + charset.toLowerCase() +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension(type) { + if (!type || typeof type !== 'string') { + return false } - return type + + // TODO: use media-typer + var match = extractTypeRegExp.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup(path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps(extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType(type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' + && from > to || (from === to && types[extension].substr(0, 12) === 'application/')) { + // skip the remapping + return + } + } + + // set the extension -> mime + types[extension] = type + } + }) } diff --git a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md old mode 100755 new mode 100644 index 3c667481..415a8cf6 --- a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md +++ b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md @@ -1,3 +1,57 @@ +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + 1.8.0 / 2015-03-13 ================== diff --git a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md old mode 100755 new mode 100644 index 1dde2349..faf387f9 --- a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md +++ b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md @@ -13,6 +13,7 @@ It aggregates data from the following sources: - http://www.iana.org/assignments/media-types/media-types.xhtml - http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types ## Installation @@ -20,8 +21,12 @@ It aggregates data from the following sources: npm install mime-db ``` -If you're crazy enough to use this in the browser, -you can just grab the JSON file: +### Database Download + +If you're crazy enough to use this in the browser, you can just grab the +JSON file using [RawGit](https://rawgit.com/). It is recommended to replace +`master` with [a release tag](https://github.com/jshttp/mime-db/tags) as the +JSON format may change in the future. ``` https://cdn.rawgit.com/jshttp/mime-db/master/db.json @@ -45,6 +50,7 @@ Each mime type has the following properties: If not set, it's probably a custom media type. - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) - `.extensions[]` - known extensions associated with this mime type. - `.compressible` - whether a file of this type is can be gzipped. - `.charset` - the default charset associated with this type, if any. @@ -65,12 +71,12 @@ them with the IANA. The community registration procedure is outlined in [RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types registered with the IANA are automatically pulled into this library. -[npm-version-image]: https://img.shields.io/npm/v/mime-db.svg?style=flat -[npm-downloads-image]: https://img.shields.io/npm/dm/mime-db.svg?style=flat +[npm-version-image]: https://img.shields.io/npm/v/mime-db.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/mime-db.svg [npm-url]: https://npmjs.org/package/mime-db -[travis-image]: https://img.shields.io/travis/jshttp/mime-db.svg?style=flat +[travis-image]: https://img.shields.io/travis/jshttp/mime-db/master.svg [travis-url]: https://travis-ci.org/jshttp/mime-db -[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-db.svg?style=flat +[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-db/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master -[node-image]: https://img.shields.io/node/v/mime-db.svg?style=flat +[node-image]: https://img.shields.io/node/v/mime-db.svg [node-url]: http://nodejs.org/download/ diff --git a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json old mode 100755 new mode 100644 index f9f3515b..27cb4a1b --- a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json +++ b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json @@ -105,6 +105,10 @@ "application/batch-smtp": { "source": "iana" }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, "application/beep+xml": { "source": "iana" }, @@ -410,7 +414,7 @@ "application/java-archive": { "source": "apache", "compressible": false, - "extensions": ["jar"] + "extensions": ["jar","war","ear"] }, "application/java-serialized-object": { "source": "apache", @@ -513,6 +517,11 @@ "source": "iana", "extensions": ["mads"] }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, "application/marc": { "source": "iana", "extensions": ["mrc"] @@ -685,7 +694,7 @@ "application/octet-stream": { "source": "iana", "compressible": false, - "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","buffer"] + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] }, "application/oda": { "source": "iana", @@ -1307,6 +1316,9 @@ "application/vnd.balsamiq.bmml+xml": { "source": "iana" }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, "application/vnd.bekitzur-stech+json": { "source": "iana", "compressible": true @@ -2029,7 +2041,12 @@ "source": "iana" }, "application/vnd.hydrostatix.sof-data": { - "source": "iana" + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true }, "application/vnd.hzn-3d-crossword": { "source": "iana" @@ -2374,6 +2391,10 @@ "source": "iana", "extensions": ["mfm"] }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, "application/vnd.micrografx.flo": { "source": "iana", "extensions": ["flo"] @@ -2382,6 +2403,9 @@ "source": "iana", "extensions": ["igx"] }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, "application/vnd.miele+json": { "source": "iana", "compressible": true @@ -2713,7 +2737,8 @@ "extensions": ["ngdat"] }, "application/vnd.nokia.n-gage.symbian.install": { - "source": "iana" + "source": "iana", + "extensions": ["n-gage"] }, "application/vnd.nokia.ncd": { "source": "iana" @@ -4068,6 +4093,10 @@ "source": "apache", "extensions": ["bcpio"] }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, "application/x-bittorrent": { "source": "apache", "extensions": ["torrent"] @@ -4109,6 +4138,10 @@ "application/x-chrome-extension": { "extensions": ["crx"] }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, "application/x-compress": { "source": "apache" }, @@ -4263,6 +4296,10 @@ "source": "apache", "extensions": ["iso"] }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, "application/x-java-jnlp-file": { "source": "apache", "compressible": false, @@ -4283,6 +4320,10 @@ "source": "apache", "extensions": ["lzh","lha"] }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, "application/x-mie": { "source": "apache", "extensions": ["mie"] @@ -4366,10 +4407,22 @@ "source": "apache", "extensions": ["nc","cdf"] }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, "application/x-nzb": { "source": "apache", "extensions": ["nzb"] }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, "application/x-pkcs12": { "source": "apache", "compressible": false, @@ -4388,10 +4441,18 @@ "compressible": false, "extensions": ["rar"] }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, "application/x-research-info-systems": { "source": "apache", "extensions": ["ris"] }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, "application/x-sh": { "source": "apache", "compressible": true, @@ -4450,7 +4511,7 @@ }, "application/x-tcl": { "source": "apache", - "extensions": ["tcl"] + "extensions": ["tcl","tk"] }, "application/x-tex": { "source": "apache", @@ -4486,7 +4547,7 @@ }, "application/x-x509-ca-cert": { "source": "apache", - "extensions": ["der","crt"] + "extensions": ["der","crt","pem"] }, "application/x-xfig": { "source": "apache", @@ -4554,7 +4615,7 @@ "extensions": ["xhtml","xht"] }, "application/xhtml-voice+xml": { - "source": "iana" + "source": "apache" }, "application/xml": { "source": "iana", @@ -4855,7 +4916,7 @@ "extensions": ["oga","ogg","spx"] }, "audio/opus": { - "source": "apache" + "source": "iana" }, "audio/parityfec": { "source": "iana" @@ -5081,6 +5142,14 @@ "audio/vorbis-config": { "source": "iana" }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, "audio/webm": { "source": "apache", "compressible": false, @@ -5104,6 +5173,10 @@ "source": "apache", "extensions": ["flac"] }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, "audio/x-matroska": { "source": "apache", "extensions": ["mka"] @@ -5128,6 +5201,10 @@ "source": "apache", "extensions": ["rmp"] }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, "audio/x-tta": { "source": "apache" }, @@ -5355,6 +5432,9 @@ "source": "iana", "extensions": ["xif"] }, + "image/vnd.zbrush.pcx": { + "source": "iana" + }, "image/webp": { "source": "apache", "extensions": ["webp"] @@ -5380,10 +5460,19 @@ "compressible": true, "extensions": ["ico"] }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, "image/x-mrsid-image": { "source": "apache", "extensions": ["sid"] }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, "image/x-pcx": { "source": "apache", "extensions": ["pcx"] @@ -5647,7 +5736,7 @@ "compressible": true }, "text/coffeescript": { - "extensions": ["coffee"] + "extensions": ["coffee","litcoffee"] }, "text/css": { "source": "iana", @@ -5689,7 +5778,7 @@ "text/html": { "source": "iana", "compressible": true, - "extensions": ["html","htm"] + "extensions": ["html","htm","shtml"] }, "text/jade": { "extensions": ["jade"] @@ -5711,6 +5800,10 @@ "text/markdown": { "source": "iana" }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, "text/mizar": { "source": "iana" }, @@ -5755,7 +5848,9 @@ "extensions": ["rtx"] }, "text/rtf": { - "source": "iana" + "source": "iana", + "compressible": true, + "extensions": ["rtf"] }, "text/rtp-enc-aescm128": { "source": "iana" @@ -5916,6 +6011,7 @@ "extensions": ["c","cc","cxx","cpp","h","hh","dic"] }, "text/x-component": { + "source": "nginx", "extensions": ["htc"] }, "text/x-fortran": { @@ -5982,7 +6078,8 @@ }, "text/xml": { "source": "iana", - "compressible": true + "compressible": true, + "extensions": ["xml"] }, "text/xml-external-parsed-entity": { "source": "iana" @@ -5995,7 +6092,7 @@ }, "video/3gpp": { "source": "apache", - "extensions": ["3gp"] + "extensions": ["3gp","3gpp"] }, "video/3gpp-tt": { "source": "apache" diff --git a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json old mode 100755 new mode 100644 index 70438aca..44884d2a --- a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json +++ b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json @@ -1,7 +1,7 @@ { "name": "mime-db", "description": "Media Type Database", - "version": "1.8.0", + "version": "1.13.0", "contributors": [ { "name": "Douglas Christopher Wilson", @@ -30,17 +30,17 @@ ], "repository": { "type": "git", - "url": "https://github.com/jshttp/mime-db" + "url": "git://github.com/jshttp/mime-db" }, "devDependencies": { - "bluebird": "~2.9.14", - "co": "~4.4.0", - "cogent": "1", - "csv-parse": "0.0.9", + "bluebird": "2.9.27", + "co": "4.5.4", + "cogent": "1.0.1", + "csv-parse": "0.1.2", "gnode": "0.1.1", - "istanbul": "0.3.7", - "mocha": "~1.21.4", - "raw-body": "~1.3.3", + "istanbul": "0.3.14", + "mocha": "1.21.5", + "raw-body": "2.1.0", "stream-to-array": "2" }, "files": [ @@ -55,39 +55,21 @@ }, "scripts": { "build": "node scripts/build", - "fetch": "gnode scripts/extensions && gnode scripts/types", + "fetch": "gnode scripts/fetch-apache && gnode scripts/fetch-iana && gnode scripts/fetch-nginx", "test": "mocha --reporter spec --bail --check-leaks test/", "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", "update": "npm run fetch && npm run build" }, - "gitHead": "cd5730a475ff03d2ef49fc571d5510a548b63494", + "readme": "# mime-db\n\n[![NPM Version][npm-version-image]][npm-url]\n[![NPM Downloads][npm-downloads-image]][npm-url]\n[![Node.js Version][node-image]][node-url]\n[![Build Status][travis-image]][travis-url]\n[![Coverage Status][coveralls-image]][coveralls-url]\n\nThis is a database of all mime types.\nIt consists of a single, public JSON file and does not include any logic,\nallowing it to remain as un-opinionated as possible with an API.\nIt aggregates data from the following sources:\n\n- http://www.iana.org/assignments/media-types/media-types.xhtml\n- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types\n- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types\n\n## Installation\n\n```bash\nnpm install mime-db\n```\n\n### Database Download\n\nIf you're crazy enough to use this in the browser, you can just grab the\nJSON file using [RawGit](https://rawgit.com/). It is recommended to replace\n`master` with [a release tag](https://github.com/jshttp/mime-db/tags) as the\nJSON format may change in the future.\n\n```\nhttps://cdn.rawgit.com/jshttp/mime-db/master/db.json\n```\n\n## Usage\n\n```js\nvar db = require('mime-db');\n\n// grab data on .js files\nvar data = db['application/javascript'];\n```\n\n## Data Structure\n\nThe JSON file is a map lookup for lowercased mime types.\nEach mime type has the following properties:\n\n- `.source` - where the mime type is defined.\n If not set, it's probably a custom media type.\n - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types)\n - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml)\n - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types)\n- `.extensions[]` - known extensions associated with this mime type.\n- `.compressible` - whether a file of this type is can be gzipped.\n- `.charset` - the default charset associated with this type, if any.\n\nIf unknown, every property could be `undefined`.\n\n## Contributing\n\nTo edit the database, only make PRs against `src/custom.json` or\n`src/custom-suffix.json`.\n\nTo update the build, run `npm run update`.\n\n## Adding Custom Media Types\n\nThe best way to get new media types included in this library is to register\nthem with the IANA. The community registration procedure is outlined in\n[RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types\nregistered with the IANA are automatically pulled into this library.\n\n[npm-version-image]: https://img.shields.io/npm/v/mime-db.svg\n[npm-downloads-image]: https://img.shields.io/npm/dm/mime-db.svg\n[npm-url]: https://npmjs.org/package/mime-db\n[travis-image]: https://img.shields.io/travis/jshttp/mime-db/master.svg\n[travis-url]: https://travis-ci.org/jshttp/mime-db\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-db/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master\n[node-image]: https://img.shields.io/node/v/mime-db.svg\n[node-url]: http://nodejs.org/download/\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/mime-db/issues" }, - "homepage": "https://github.com/jshttp/mime-db", - "_id": "mime-db@1.8.0", - "_shasum": "82a9b385f22b0f5954dec4d445faba0722c4ad25", - "_from": "mime-db@~1.8.0", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], + "_id": "mime-db@1.13.0", "dist": { - "shasum": "82a9b385f22b0f5954dec4d445faba0722c4ad25", - "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.8.0.tgz" + "shasum": "b6b90fbdab177a601068c884408bea3118e3f407" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.8.0.tgz" + "_from": "mime-db@~1.13.0", + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.13.0.tgz" } diff --git a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json old mode 100755 new mode 100644 index 5fe0d5d1..7605a8b7 --- a/server/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json +++ b/server/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json @@ -1,7 +1,7 @@ { "name": "mime-types", "description": "The ultimate javascript content-type utility.", - "version": "2.0.10", + "version": "2.1.1", "contributors": [ { "name": "Douglas Christopher Wilson", @@ -25,13 +25,13 @@ ], "repository": { "type": "git", - "url": "https://github.com/jshttp/mime-types" + "url": "git://github.com/jshttp/mime-types" }, "dependencies": { - "mime-db": "~1.8.0" + "mime-db": "~1.13.0" }, "devDependencies": { - "istanbul": "0.3.7", + "istanbul": "0.3.14", "mocha": "~1.21.5" }, "files": [ @@ -47,37 +47,15 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/test.js", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot test/test.js" }, - "gitHead": "9d4533a2b3a68af48a7f3ded9f8f525648e7bcc1", + "readme": "# mime-types\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nThe ultimate javascript content-type utility.\n\nSimilar to [node-mime](https://github.com/broofa/node-mime), except:\n\n- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`,\n so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`.\n- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`.\n- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db)\n- No `.define()` functionality\n\nOtherwise, the API is compatible.\n\n## Install\n\n```sh\n$ npm install mime-types\n```\n\n## Adding Types\n\nAll mime types are based on [mime-db](https://github.com/jshttp/mime-db),\nso open a PR there if you'd like to add mime types.\n\n## API\n\n```js\nvar mime = require('mime-types')\n```\n\nAll functions return `false` if input is invalid or not found.\n\n### mime.lookup(path)\n\nLookup the content-type associated with a file.\n\n```js\nmime.lookup('json') // 'application/json'\nmime.lookup('.md') // 'text/x-markdown'\nmime.lookup('file.html') // 'text/html'\nmime.lookup('folder/file.js') // 'application/javascript'\nmime.lookup('folder/.htaccess') // false\n\nmime.lookup('cats') // false\n```\n\n### mime.contentType(type)\n\nCreate a full content-type header given a content-type or extension.\n\n```js\nmime.contentType('markdown') // 'text/x-markdown; charset=utf-8'\nmime.contentType('file.json') // 'application/json; charset=utf-8'\n\n// from a full path\nmime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8'\n```\n\n### mime.extension(type)\n\nGet the default extension for a content-type.\n\n```js\nmime.extension('application/octet-stream') // 'bin'\n```\n\n### mime.charset(type)\n\nLookup the implied default charset of a content-type.\n\n```js\nmime.charset('text/x-markdown') // 'UTF-8'\n```\n\n### var type = mime.types[extension]\n\nA map of content-types by extension.\n\n### [extensions...] = mime.extensions[type]\n\nA map of extensions by content-type.\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/mime-types.svg\n[npm-url]: https://npmjs.org/package/mime-types\n[node-version-image]: https://img.shields.io/node/v/mime-types.svg\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/mime-types/master.svg\n[travis-url]: https://travis-ci.org/jshttp/mime-types\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-types/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/mime-types\n[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg\n[downloads-url]: https://npmjs.org/package/mime-types\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/mime-types/issues" }, - "homepage": "https://github.com/jshttp/mime-types", - "_id": "mime-types@2.0.10", - "_shasum": "eacd81bb73cab2a77447549a078d4f2018c67b4d", - "_from": "mime-types@~2.0.4", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "fishrock123", - "email": "fishrock123@rocketmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], + "_id": "mime-types@2.1.1", "dist": { - "shasum": "eacd81bb73cab2a77447549a078d4f2018c67b4d", - "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.0.10.tgz" + "shasum": "07341942622db6e106a6f7f83922c1fdc54051cc" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.0.10.tgz" + "_from": "mime-types@~2.1.1", + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.1.tgz" } diff --git a/server/node_modules/express/node_modules/type-is/package.json b/server/node_modules/express/node_modules/type-is/package.json old mode 100755 new mode 100644 index 2d140a38..d20e8ea5 --- a/server/node_modules/express/node_modules/type-is/package.json +++ b/server/node_modules/express/node_modules/type-is/package.json @@ -1,29 +1,29 @@ { "name": "type-is", "description": "Infer the content-type of a request.", - "version": "1.5.7", - "author": { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, + "version": "1.6.3", "contributors": [ { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" } ], "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/jshttp/type-is" + "url": "git://github.com/jshttp/type-is" }, "dependencies": { "media-typer": "0.3.0", - "mime-types": "~2.0.9" + "mime-types": "~2.1.1" }, "devDependencies": { - "istanbul": "0.3.5", + "istanbul": "0.3.14", "mocha": "~1.21.5" }, "engines": { @@ -44,49 +44,15 @@ "type", "checking" ], - "gitHead": "f4335cc563a98ee80366f04f67c50cef089ae803", + "readme": "# type-is\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nInfer the content-type of a request.\n\n### Install\n\n```sh\n$ npm install type-is\n```\n\n## API\n\n```js\nvar http = require('http')\nvar is = require('type-is')\n\nhttp.createServer(function (req, res) {\n var istext = is(req, ['text/*'])\n res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text')\n})\n```\n\n### type = is(request, types)\n\n`request` is the node HTTP request. `types` is an array of types.\n\n```js\n// req.headers.content-type = 'application/json'\n\nis(req, ['json']) // 'json'\nis(req, ['html', 'json']) // 'json'\nis(req, ['application/*']) // 'application/json'\nis(req, ['application/json']) // 'application/json'\n\nis(req, ['html']) // false\n```\n\n### type = is.is(mediaType, types)\n\n`mediaType` is the [media type](https://tools.ietf.org/html/rfc6838) string. `types` is an array of types.\n\n```js\nvar mediaType = 'application/json'\n\nis.is(mediaType, ['json']) // 'json'\nis.is(mediaType, ['html', 'json']) // 'json'\nis.is(mediaType, ['application/*']) // 'application/json'\nis.is(mediaType, ['application/json']) // 'application/json'\n\nis.is(mediaType, ['html']) // false\n```\n\n### Each type can be:\n\n- An extension name such as `json`. This name will be returned if matched.\n- A mime type such as `application/json`.\n- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. The full mime type will be returned if matched.\n- A suffix such as `+json`. This can be combined with a wildcard such as `*/vnd+json` or `application/*+json`. The full mime type will be returned if matched.\n\n`false` will be returned if no type matches or the content type is invalid.\n\n`null` will be returned if the request does not have a body.\n\n## Examples\n\n#### Example body parser\n\n```js\nvar is = require('type-is');\n\nfunction bodyParser(req, res, next) {\n if (!is.hasBody(req)) {\n return next()\n }\n\n switch (is(req, ['urlencoded', 'json', 'multipart'])) {\n case 'urlencoded':\n // parse urlencoded body\n throw new Error('implement urlencoded body parsing')\n break\n case 'json':\n // parse json body\n throw new Error('implement json body parsing')\n break\n case 'multipart':\n // parse multipart body\n throw new Error('implement multipart body parsing')\n break\n default:\n // 415 error code\n res.statusCode = 415\n res.end()\n return\n }\n}\n```\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/type-is.svg\n[npm-url]: https://npmjs.org/package/type-is\n[node-version-image]: https://img.shields.io/node/v/type-is.svg\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/type-is/master.svg\n[travis-url]: https://travis-ci.org/jshttp/type-is\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/type-is/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/type-is.svg\n[downloads-url]: https://npmjs.org/package/type-is\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/type-is/issues" }, - "homepage": "https://github.com/jshttp/type-is", - "_id": "type-is@1.5.7", - "_shasum": "b9368a593cc6ef7d0645e78b2f4c64cbecd05e90", - "_from": "type-is@~1.5.3", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "shtylman", - "email": "shtylman@gmail.com" - }, - { - "name": "mscdex", - "email": "mscdex@mscdex.net" - }, - { - "name": "fishrock123", - "email": "fishrock123@rocketmail.com" - } - ], + "_id": "type-is@1.6.3", "dist": { - "shasum": "b9368a593cc6ef7d0645e78b2f4c64cbecd05e90", - "tarball": "http://registry.npmjs.org/type-is/-/type-is-1.5.7.tgz" + "shasum": "629be893a04171a15825efc0ab4a5d0e6c5b1eb5" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/type-is/-/type-is-1.5.7.tgz" + "_from": "type-is@~1.6.2", + "_resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.3.tgz" } diff --git a/server/node_modules/express/node_modules/utils-merge/.travis.yml b/server/node_modules/express/node_modules/utils-merge/.travis.yml old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/utils-merge/LICENSE b/server/node_modules/express/node_modules/utils-merge/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/utils-merge/README.md b/server/node_modules/express/node_modules/utils-merge/README.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/utils-merge/index.js b/server/node_modules/express/node_modules/utils-merge/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/utils-merge/package.json b/server/node_modules/express/node_modules/utils-merge/package.json old mode 100755 new mode 100644 index 305d5e10..f8d5fc62 --- a/server/node_modules/express/node_modules/utils-merge/package.json +++ b/server/node_modules/express/node_modules/utils-merge/package.json @@ -30,31 +30,13 @@ "chai": "1.x.x" }, "scripts": { - "test": "mocha --reporter spec --require test/bootstrap/node test/*.test.js" + "test": "node_modules/.bin/mocha --reporter spec --require test/bootstrap/node test/*.test.js" }, "engines": { "node": ">= 0.4.0" }, + "readme": "# utils-merge\n\nMerges the properties from a source object into a destination object.\n\n## Install\n\n $ npm install utils-merge\n\n## Usage\n\n```javascript\nvar a = { foo: 'bar' }\n , b = { bar: 'baz' };\n\nmerge(a, b);\n// => { foo: 'bar', bar: 'baz' }\n```\n\n## Tests\n\n $ npm install\n $ npm test\n\n[![Build Status](https://secure.travis-ci.org/jaredhanson/utils-merge.png)](http://travis-ci.org/jaredhanson/utils-merge)\n\n## Credits\n\n - [Jared Hanson](http://github.com/jaredhanson)\n\n## License\n\n[The MIT License](http://opensource.org/licenses/MIT)\n\nCopyright (c) 2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)>\n", + "readmeFilename": "README.md", "_id": "utils-merge@1.0.0", - "dist": { - "shasum": "0294fb922bb9375153541c4f7096231f287c8af8", - "tarball": "http://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz" - }, - "_from": "utils-merge@1.0.0", - "_npmVersion": "1.2.25", - "_npmUser": { - "name": "jaredhanson", - "email": "jaredhanson@gmail.com" - }, - "maintainers": [ - { - "name": "jaredhanson", - "email": "jaredhanson@gmail.com" - } - ], - "directories": {}, - "_shasum": "0294fb922bb9375153541c4f7096231f287c8af8", - "_resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz", - "readme": "ERROR: No README data found!", - "homepage": "https://github.com/jaredhanson/utils-merge" + "_from": "utils-merge@1.0.0" } diff --git a/server/node_modules/express/node_modules/vary/.npmignore b/server/node_modules/express/node_modules/vary/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/vary/History.md b/server/node_modules/express/node_modules/vary/History.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/vary/LICENSE b/server/node_modules/express/node_modules/vary/LICENSE old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/vary/README.md b/server/node_modules/express/node_modules/vary/README.md old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/vary/index.js b/server/node_modules/express/node_modules/vary/index.js old mode 100755 new mode 100644 diff --git a/server/node_modules/express/node_modules/vary/package.json b/server/node_modules/express/node_modules/vary/package.json old mode 100755 new mode 100644 index 4c4bd623..5810cccd --- a/server/node_modules/express/node_modules/vary/package.json +++ b/server/node_modules/express/node_modules/vary/package.json @@ -14,7 +14,7 @@ ], "repository": { "type": "git", - "url": "https://github.com/jshttp/vary" + "url": "git://github.com/jshttp/vary" }, "devDependencies": { "istanbul": "0.3.0", @@ -30,42 +30,11 @@ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" }, - "gitHead": "56acecd9fa20888132563b00576625ea02a69a35", + "readme": "# vary\n\n[![NPM Version](http://img.shields.io/npm/v/vary.svg?style=flat)](https://www.npmjs.org/package/vary)\n[![Node.js Version](http://img.shields.io/badge/node.js->=_0.8-blue.svg?style=flat)](http://nodejs.org/download/)\n[![Build Status](http://img.shields.io/travis/jshttp/vary.svg?style=flat)](https://travis-ci.org/jshttp/vary)\n[![Coverage Status](https://img.shields.io/coveralls/jshttp/vary.svg?style=flat)](https://coveralls.io/r/jshttp/vary)\n[![Gittip](http://img.shields.io/gittip/dougwilson.svg?style=flat)](https://www.gittip.com/dougwilson/)\n\nManipulate the HTTP Vary header\n\n## Install\n\n```sh\n$ npm install vary\n```\n\n## API\n\n```js\nvar vary = require('vary')\n```\n\n### vary(res, field)\n\nAdds the given header `field` to the `Vary` response header of `res`.\nThis can be a string of a single field, a string of a valid `Vary`\nheader, or an array of multiple fields.\n\nThis will append the header if not already listed, otherwise leaves\nit listed in the current location.\n\n```js\n// Append \"Origin\" to the Vary header of the response\nvary(res, 'Origin')\n```\n\n### vary.append(header, field)\n\nAdds the given header `field` to the `Vary` response header string `header`.\nThis can be a string of a single field, a string of a valid `Vary` header,\nor an array of multiple fields.\n\nThis will append the header if not already listed, otherwise leaves\nit listed in the current location. The new header string is returned.\n\n```js\n// Get header string appending \"Origin\" to \"Accept, User-Agent\"\nvary.append('Accept, User-Agent', 'Origin')\n```\n\n## Testing\n\n```sh\n$ npm test\n```\n\n## License\n\n[MIT](LICENSE)\n", + "readmeFilename": "README.md", "bugs": { "url": "https://github.com/jshttp/vary/issues" }, - "homepage": "https://github.com/jshttp/vary", "_id": "vary@1.0.0", - "_shasum": "c5e76cec20d3820d8f2a96e7bee38731c34da1e7", - "_from": "vary@~1.0.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "fishrock123", - "email": "fishrock123@rocketmail.com" - }, - { - "name": "shtylman", - "email": "shtylman@gmail.com" - } - ], - "dist": { - "shasum": "c5e76cec20d3820d8f2a96e7bee38731c34da1e7", - "tarball": "http://registry.npmjs.org/vary/-/vary-1.0.0.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/vary/-/vary-1.0.0.tgz", - "readme": "ERROR: No README data found!" + "_from": "vary@~1.0.0" } diff --git a/server/node_modules/express/package.json b/server/node_modules/express/package.json old mode 100755 new mode 100644 index 492eb28c..278dcae3 --- a/server/node_modules/express/package.json +++ b/server/node_modules/express/package.json @@ -1,7 +1,7 @@ { "name": "express", "description": "Fast, unopinionated, minimalist web framework", - "version": "4.10.2", + "version": "4.12.4", "author": { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca" @@ -39,7 +39,7 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/strongloop/express" + "url": "git://github.com/strongloop/express" }, "homepage": "http://expressjs.com/", "keywords": [ @@ -54,48 +54,48 @@ "api" ], "dependencies": { - "accepts": "~1.1.3", + "accepts": "~1.2.7", "content-disposition": "0.5.0", - "cookie-signature": "1.0.5", - "debug": "~2.1.0", - "depd": "~1.0.0", + "content-type": "~1.0.1", + "cookie": "0.1.2", + "cookie-signature": "1.0.6", + "debug": "~2.2.0", + "depd": "~1.0.1", "escape-html": "1.0.1", - "etag": "~1.5.0", - "finalhandler": "0.3.2", + "etag": "~1.6.0", + "finalhandler": "0.3.6", "fresh": "0.2.4", - "media-typer": "0.3.0", - "methods": "1.1.0", - "on-finished": "~2.1.1", + "merge-descriptors": "1.0.0", + "methods": "~1.1.1", + "on-finished": "~2.2.1", "parseurl": "~1.3.0", "path-to-regexp": "0.1.3", - "proxy-addr": "~1.0.3", - "qs": "2.3.2", + "proxy-addr": "~1.0.8", + "qs": "2.4.2", "range-parser": "~1.0.2", - "send": "0.10.1", - "serve-static": "~1.7.1", - "type-is": "~1.5.3", + "send": "0.12.3", + "serve-static": "~1.9.3", + "type-is": "~1.6.2", "vary": "~1.0.0", - "cookie": "0.1.2", - "merge-descriptors": "0.0.2", "utils-merge": "1.0.0" }, "devDependencies": { "after": "0.8.1", - "istanbul": "0.3.2", - "mocha": "~2.0.0", - "should": "~4.2.1", - "supertest": "~0.14.0", - "ejs": "~1.0.0", - "marked": "0.3.2", - "hjs": "~0.0.6", - "body-parser": "~1.9.1", - "connect-redis": "~2.1.0", - "cookie-parser": "~1.3.3", - "express-session": "~1.9.1", - "jade": "~1.7.0", - "method-override": "~2.3.0", - "morgan": "~1.4.1", - "multiparty": "~4.0.0", + "ejs": "2.3.1", + "istanbul": "0.3.9", + "marked": "0.3.3", + "mocha": "2.2.5", + "should": "6.0.1", + "supertest": "1.0.1", + "body-parser": "~1.12.4", + "connect-redis": "~2.3.0", + "cookie-parser": "~1.3.4", + "cookie-session": "~1.1.0", + "express-session": "~1.11.2", + "jade": "~1.9.2", + "method-override": "~2.3.3", + "morgan": "~1.5.3", + "multiparty": "~4.1.2", "vhost": "~3.0.0" }, "engines": { @@ -110,57 +110,19 @@ ], "scripts": { "test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/", "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/", - "test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/" + "test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/" }, - "gitHead": "ac56cf46063e461fbaf53c2c869a1a657e8adbe1", + "readme": "[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/)\n\n Fast, unopinionated, minimalist web framework for [node](http://nodejs.org).\n\n [![NPM Version][npm-image]][npm-url]\n [![NPM Downloads][downloads-image]][downloads-url]\n [![Linux Build][travis-image]][travis-url]\n [![Windows Build][appveyor-image]][appveyor-url]\n [![Test Coverage][coveralls-image]][coveralls-url]\n\n```js\nvar express = require('express')\nvar app = express()\n\napp.get('/', function (req, res) {\n res.send('Hello World')\n})\n\napp.listen(3000)\n```\n\n## Installation\n\n```bash\n$ npm install express\n```\n\n## Features\n\n * Robust routing\n * Focus on high performance\n * Super-high test coverage\n * HTTP helpers (redirection, caching, etc)\n * View system supporting 14+ template engines\n * Content negotiation\n * Executable for generating applications quickly\n\n## Docs & Community\n\n * [Website and Documentation](http://expressjs.com/) - [[website repo](https://github.com/strongloop/expressjs.com)]\n * [#express](https://webchat.freenode.net/?channels=express) on freenode IRC\n * [Github Organization](https://github.com/expressjs) for Official Middleware & Modules\n * Visit the [Wiki](https://github.com/strongloop/express/wiki)\n * [Google Group](https://groups.google.com/group/express-js) for discussion\n * [Русскоязычная документация](http://jsman.ru/express/)\n * [한국어 문서](http://expressjs.kr) - [[website repo](https://github.com/Hanul/expressjs.kr)]\n\n**PROTIP** Be sure to read [Migrating from 3.x to 4.x](https://github.com/strongloop/express/wiki/Migrating-from-3.x-to-4.x) as well as [New features in 4.x](https://github.com/strongloop/express/wiki/New-features-in-4.x).\n\n## Quick Start\n\n The quickest way to get started with express is to utilize the executable [`express(1)`](https://github.com/expressjs/generator) to generate an application as shown below:\n\n Install the executable. The executable's major version will match Express's:\n\n```bash\n$ npm install -g express-generator@4\n```\n\n Create the app:\n\n```bash\n$ express /tmp/foo && cd /tmp/foo\n```\n\n Install dependencies:\n\n```bash\n$ npm install\n```\n\n Start the server:\n\n```bash\n$ npm start\n```\n\n## Philosophy\n\n The Express philosophy is to provide small, robust tooling for HTTP servers, making\n it a great solution for single page applications, web sites, hybrids, or public\n HTTP APIs.\n\n Express does not force you to use any specific ORM or template engine. With support for over\n 14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js),\n you can quickly craft your perfect framework.\n\n## Examples\n\n To view the examples, clone the Express repo and install the dependencies:\n\n```bash\n$ git clone git://github.com/strongloop/express.git --depth 1\n$ cd express\n$ npm install\n```\n\n Then run whichever example you want:\n\n```bash\n$ node examples/content-negotiation\n```\n\n## Tests\n\n To run the test suite, first install the dependencies, then run `npm test`:\n\n```bash\n$ npm install\n$ npm test\n```\n\n## People\n\nThe original author of Express is [TJ Holowaychuk](https://github.com/tj) [![TJ's Gratipay][gratipay-image-visionmedia]][gratipay-url-visionmedia]\n\nThe current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson) [![Doug's Gratipay][gratipay-image-dougwilson]][gratipay-url-dougwilson]\n\n[List of all contributors](https://github.com/strongloop/express/graphs/contributors)\n\n## License\n\n [MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/express.svg\n[npm-url]: https://npmjs.org/package/express\n[downloads-image]: https://img.shields.io/npm/dm/express.svg\n[downloads-url]: https://npmjs.org/package/express\n[travis-image]: https://img.shields.io/travis/strongloop/express/master.svg?label=linux\n[travis-url]: https://travis-ci.org/strongloop/express\n[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/express/master.svg?label=windows\n[appveyor-url]: https://ci.appveyor.com/project/dougwilson/express\n[coveralls-image]: https://img.shields.io/coveralls/strongloop/express/master.svg\n[coveralls-url]: https://coveralls.io/r/strongloop/express?branch=master\n[gratipay-image-visionmedia]: https://img.shields.io/gratipay/visionmedia.svg\n[gratipay-url-visionmedia]: https://gratipay.com/visionmedia/\n[gratipay-image-dougwilson]: https://img.shields.io/gratipay/dougwilson.svg\n[gratipay-url-dougwilson]: https://gratipay.com/dougwilson/\n", + "readmeFilename": "Readme.md", "bugs": { "url": "https://github.com/strongloop/express/issues" }, - "_id": "express@4.10.2", - "_shasum": "df06dde94d968932829d440a2004c5efe64495b0", - "_from": "express@4.10.2", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "shtylman", - "email": "shtylman@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "aredridel", - "email": "aredridel@nbtsc.org" - }, - { - "name": "strongloop", - "email": "callback@strongloop.com" - }, - { - "name": "rfeng", - "email": "enjoyjava@gmail.com" - } - ], + "_id": "express@4.12.4", "dist": { - "shasum": "df06dde94d968932829d440a2004c5efe64495b0", - "tarball": "http://registry.npmjs.org/express/-/express-4.10.2.tgz" + "shasum": "c06eadfedcf35a26ff449314fb84e24f54cdb129" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/express/-/express-4.10.2.tgz", - "readme": "ERROR: No README data found!" + "_from": "express@4.12.4", + "_resolved": "https://registry.npmjs.org/express/-/express-4.12.4.tgz" } diff --git a/server/node_modules/monk/.npmignore b/server/node_modules/monk/.npmignore deleted file mode 100755 index 7dccd970..00000000 --- a/server/node_modules/monk/.npmignore +++ /dev/null @@ -1,15 +0,0 @@ -lib-cov -*.seed -*.log -*.csv -*.dat -*.out -*.pid -*.gz - -pids -logs -results - -node_modules -npm-debug.log \ No newline at end of file diff --git a/server/node_modules/monk/.travis.yml b/server/node_modules/monk/.travis.yml deleted file mode 100755 index 7fd17937..00000000 --- a/server/node_modules/monk/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 -services: mongodb diff --git a/server/node_modules/monk/History.md b/server/node_modules/monk/History.md deleted file mode 100755 index 7592d348..00000000 --- a/server/node_modules/monk/History.md +++ /dev/null @@ -1,181 +0,0 @@ - -1.0.1 / 2015-03-25 -================== - - * upgrade; mongoskin to 1.4.13 - -0.9.2 / 2015-02-28 -================== - - * mongoskin: bump to 1.4.11 - * Inserting an array returns an array - * Cast oids inside of $nor queries - * Cast object ids inside of $or and $and queries - * Cast object ids inside of $not queries - * Added a missing test for updateById - * Added removeById - * Use `setImmediate` on node 0.10.x - -0.9.1 / 2014-11-15 -================== - - * update mongoskin to 1.4.4 - -0.9.0 / 2014-05-09 -================== - - * addition of `close()` method - * updaet mongoskin 1.4.1 - * fixed URL parsing of replsets - * freezed mpromise version - * fixed collection distinct after rebase - * reimplemented Monk.Promise with MPromise. - -0.8.1 / 2014-03-01 -================== - - * fix for parameter handling in `findAndModify` - * check for `uri` parameter or throw - -0.8.0 / 2014-03-01 -================== - - * added `distinct` support (fixes #52) - * added `Promise#then` - -0.7.1 / 2013-03-03 -================== - - * promise: expose `query` - -0.7.0 / 2012-10-30 -================== - - *: bumped `mongoskin` and therefore `node-mongodb-native` - -0.6.0 / 2012-10-29 -================== - - * collection: added cursor closing support - * promise: introduce #destroy - * test: added cursor destroy test - -0.5.0 / 2012-10-03 -================== - - * promise: added opts to constructor - * util: fix field negation - * test: added test for promise options - * collection: pass options to promises - -0.4.0 / 2012-10-03 -================== - - * added travis - * manager: added Manager#id and Manager#oid - * collection: introduced Collection#oid - * manager: added Manager#col - -0.3.0 / 2012-09-06 -================== - - * collection: make `findAndModify` accept an oid as the query - -0.2.1 / 2012-07-14 -================== - - * collection: fixed streaming when options are not supplied - -0.2.0 / 2012-07-14 -================== - - * collection: added `count` - -0.1.15 / 2012-07-14 -=================== - - * collection: avoid mongoskin warn when buffering commands - -0.1.14 / 2012-07-09 -=================== - - * Use any debug. [visionmedia] - * Use any mocha. [visionmedia] - -0.1.13 / 2012-05-28 -=================== - - * Fixed string-based field selection. - -0.1.12 / 2012-05-25 -=================== - - * Added package.json tags. - * Added support for update with ids (fixes #4) - -0.1.11 / 2012-05-22 -=================== - - * Added support for new objectids through `Collection#id` - -0.1.10 / 2012-05-21 -=================== - - * Enhanced findAndModify default behavior for upserts. - * Fixed findAndModify. - -0.1.9 / 2012-05-16 -================== - - * Bumped mongoskin - -0.1.8 / 2012-05-12 -================== - - * Fixed mongoskin version - * Improved options docs section. - -0.1.7 / 2012-05-08 -================== - - * Added global and collection-level options. - * Enabled safe mode by default. - * Improved error handling in tests. - * Fixed `update` callback with safe: false. - -0.1.6 / 2012-05-06 -================== - - * Added tests for `findById`. - -0.1.5 / 2012-05-06 -================== - - * Added `Collection` references to `Promise`s. - * Fixed `findAndModify`. - -0.1.4 / 2012-05-06 -================== - - * Ensured insert calls back with a single object. - * Ensured `insert` resolves promise in next tick. - -0.1.3 / 2012-05-03 -================== - - * Exposed `util` - -0.1.2 / 2012-05-03 -================== - - * Make `Collection` inherit from `EventEmitter`. - -0.1.1 / 2012-04-27 -================== - - * Added `updateById`. - -0.1.0 / 2012-04-23 -================== - - * Initial release. diff --git a/server/node_modules/monk/Makefile b/server/node_modules/monk/Makefile deleted file mode 100755 index dab95a5c..00000000 --- a/server/node_modules/monk/Makefile +++ /dev/null @@ -1,27 +0,0 @@ - -TESTS = test/*.test.js -REPORTER = dot - -test: - @make --no-print-directory test-unit - @echo "testing promises-A+ implementation ..." - @make --no-print-directory test-promises-A - -test-unit: - @DEBUG=$DEBUG,monk,monk:queries ./node_modules/.bin/mocha \ - --require test/common.js \ - --reporter $(REPORTER) \ - --growl \ - --bail \ - --slow 1000 \ - $(TESTS) - -test-promises-A: - @./node_modules/.bin/mocha \ - --reporter $(REPORTER) \ - --growl \ - --bail \ - --slow 1000 \ - test/promises-A.js - -.PHONY: test test-unit test-promises-A diff --git a/server/node_modules/monk/README.md b/server/node_modules/monk/README.md deleted file mode 100755 index 076fd512..00000000 --- a/server/node_modules/monk/README.md +++ /dev/null @@ -1,250 +0,0 @@ -# monk - -[![build status](https://secure.travis-ci.org/Automattic/monk.png?branch=master)](https://secure.travis-ci.org/Automattic/monk) - -Monk is a tiny layer that provides simple yet substantial usability -improvements for MongoDB usage within Node.JS. - -```js -var db = require('monk')('localhost/mydb'); -var users = db.get('users'); - -users.index('name last'); -users.insert({ name: 'Tobi', bigdata: {} }); -users.find({ name: 'Loki' }, '-bigdata', function () { - // exclude bigdata field -}); -users.find({}, {sort: {name: 1}}, function () { - // sorted by name field -}); -users.remove({ name: 'Loki' }); - -db.close(); -``` - -## Features - -- Command buffering. You can start querying right away. -- Promises built-in for all queries. Easy interoperability with modules. -- Easy connections / configuration -- Well-designed signatures -- Improvements to the MongoDB APIs (eg: `findAndModify` supports the - `update` signature style) -- Auto-casting of `_id` in queries -- Builds on top of [mongoskin](http://github.com/kissjs/node-mongoskin) -- Allows to set global options or collection-level options for queries. (eg: - `safe` is `true` by default for all queries) - -## How to use - -### Connecting - -#### Single server - -```js -var db = require('monk')('localhost/mydb') -``` - -#### Replica set - -```js -var db = require('monk')('localhost/mydb,192.168.1.1') -``` - -### Disconnecting - -```js -db.close() -``` - -### Collections - -#### Getting one - -```js -var users = db.get('users') -// users.insert(), users.update() … (see below) -``` - -#### Dropping - -```js -users.drop(fn); -``` - -### Signatures - -- All commands accept the simple `data[, …], fn`. For example - - `find({}, fn)` - - `findOne({}, fn)` - - `update({}, {}, fn)` `findAndModify({}, {}, fn)` - - `findById('id', fn)` - - `remove({}, fn)` -- You can pass options in the middle: `data[, …], options, fn` -- You can pass fields to select as an array: `data[, …], ['field', …], fn` -- You can pass fields as a string delimited by spaces: - `data[, …], 'field1 field2', fn` -- To exclude a field, prefix the field name with '-': - `data[, …], '-field1', fn` - -### Promises - -All methods that perform an async action return a promise. - -```js -var promise = users.insert({}); -promise.type; // 'insert' in this case -promise.error(function(err){}); -promise.on('error', function(err){}); -promise.on('success', function(doc){}); -promise.on('complete', function(err, doc){}); -promise.success(function(doc){}); -``` - -### Indexes - -```js -users.index('name.first', fn); -users.index('email', { unique: true }); // unique -users.index('name.first name.last') // compound -users.index({ 'email': 1, 'password': -1 }); // compound with sort -users.index('email', { sparse: true }, fn); // with options -users.indexes(fn); // get indexes -users.dropIndex(name, fn); // drop an index -users.dropIndexes(fn); // drop all indexes -``` - -### Inserting - -```js -users.insert({ a: 'b' }, function (err, doc) { - if (err) throw err; -}); -``` - -### Casting - -To cast to `ObjectId`: - -```js -users.id() // returns new generated ObjectID -users.id('hexstring') // returns ObjectId -users.id(obj) // returns ObjectId -``` - -### Updating - -```js -users.update({}, {}, fn); -users.updateById('id', {}, fn); -``` - -### Finding - -#### Many - -```js -users.find({}, function (err, docs){}); -``` - -#### By ID - -```js -users.findById('hex representation', function(err, doc){}); -users.findById(oid, function(err, doc){}); -``` - -#### Single doc - -`findOne` also provides the `findById` functionality. - -```js -users.findOne({ name: 'test' }).on('success', function (doc) {}); -``` - -#### And modify - -```js -users.findAndModify({ query: {}, update: {} }); -users.findAndModify({ _id: '' }, { $set: {} }); -``` - -#### Streaming - -Note: `stream: true` is optional if you register an `each` handler in the -same tick. In the following example I just include it for extra clarity. - -```js -users.find({}, { stream: true }) - .each(function(doc){}) - .error(function(err){}) - .success(function(){}); -``` - -##### Destroying a cursor - -On the returned promise you can call `destroy()`. Upon the cursor -closing the `success` event will be emitted. - -### Removing - -```js -users.remove({ a: 'b' }, function (err) { - if (err) throw err; -}); -``` - -### Global options - -```js -var db = require('monk')('localhost/mydb') -db.options.multi = true; // global multi-doc update -db.get('users').options.multi = false; // collection-level -``` - -Monk sets `safe` to `true` by default. - -### Query debugging - -If you wish to see what queries `monk` passes to the driver, simply leverage -[debug](http://github.com/visionmedia/debug): - -```bash -DEBUG="monk:queries" -``` - -To see all debugging output: - -```bash -DEBUG="monk:*" -``` - -## Contributors - -- [Guillermo Rauch](http://github.com/rauchg) -- [Travis Jeffery](http://github.com/travisjeffery) - -## License - -(The MIT License) - -Copyright (c) 2012 Guillermo Rauch <guillermo@learnboost.com> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/monk/lib/collection.js b/server/node_modules/monk/lib/collection.js deleted file mode 100755 index 75fe379f..00000000 --- a/server/node_modules/monk/lib/collection.js +++ /dev/null @@ -1,604 +0,0 @@ -/** - * Module dependencies. - */ - -var util = require('./util') - , debug = require('debug')('monk:queries') - , EventEmitter = require('events').EventEmitter - , Promise = require('./promise') - , immediately = global.setImmediate || process.nextTick; - -/** - * Module exports - */ - -module.exports = Collection; - -/** - * Collection. - * - * @api public - */ - -function Collection (manager, name) { - this.manager = manager; - this.driver = manager.driver; - this.helper = manager.helper; - this.name = name; - this.col = this.driver.collection(name); - this.col.id = this.helper.id; - this.options = {}; - this.col.emitter = this.col.emitter || this.col._emitter; - this.col.emitter.setMaxListeners(Infinity); -} - -/** - * Inherits from EventEmitter. - */ - -Collection.prototype.__proto__ = EventEmitter.prototype; - -/** - * Casts to objectid - * - * @param {Mixed} hex id or ObjectId - * @return {ObjectId} - * @api public - */ - -Collection.prototype.id = -Collection.prototype.oid = function (str) { - if (null == str) return this.col.id(); - return 'string' == typeof str ? this.col.id(str) : str; -}; - -/** - * Opts utility. - */ - -Collection.prototype.opts = function (opts) { - opts = util.options(opts || {}); - - for (var i in this.manager.options) { - if (!(i in opts) && !(i in this.options)) { - opts[i] = this.manager.options[i]; - } - } - - for (var i in this.options) { - if (!(i in opts)) { - opts[i] = this.options[i]; - } - } - - return opts; -}; - -/** - * Set up indexes. - * - * @param {Object|String|Array} fields - * @param {Object|Function} optional, options or callback - * @param {Function} optional, callback - * @return {Promise} - * @api public - */ - -Collection.prototype.index = -Collection.prototype.ensureIndex = function (fields, opts, fn) { - if ('function' == typeof opts) { - fn = opts; - opts = {}; - } - - var fields = util.fields(fields) - , opts = opts || {} - , promise = new Promise(this, 'index'); - - if (fn) { - promise.complete(fn); - } - - // query - debug('%s ensureIndex %j (%j)', this.name, fields, opts); - this.col.ensureIndex(fields, opts, promise.resolve); - - return promise; -}; - -/** - * Gets all indexes. - * - * @param {Function} callback - * @return {Promise} - * @api public - */ - -Collection.prototype.indexes = function (fn) { - var promise = new Promise(this, 'indexes'); - - if (fn) { - promise.complete(fn); - } - - // query - debug('%s indexInformation', this.name); - this.col.indexInformation(promise.resolve); - - return promise; -}; - -/** - * update - * - * @param {Object} search query - * @param {Object} update obj - * @param {Object|String|Array} optional, options or fields - * @param {Function} callback - * @return {Promise} - * @api public - */ - -Collection.prototype.update = function (search, update, opts, fn) { - if ('string' == typeof search || 'function' == typeof search.toHexString) { - return this.update({ _id: search }, update, opts, fn); - } - - if ('function' == typeof opts) { - fn = opts; - opts = {}; - } - - opts = this.opts(opts); - var promise = new Promise(this, 'update', opts); - - if (fn) { - promise.complete(fn); - } - - // cast - search = this.cast(search); - update = this.cast(update); - - // query - var callback = opts.safe ? promise.resolve : function () { - // node-mongodb-native will send err=undefined and call the fn - // in the same tick if safe: false - var args = arguments; - args[0] = args[0] || null; - immediately(function () { - promise.resolve.apply(promise, args); - }); - }; - - debug('%s update %j with %j', this.name, search, update); - promise.query = { query: search, update: update }; - this.col.update(search, update, opts, callback); - - return promise; -}; - -/** - * update by id helper - * - * @param {String|Object} object id - * @param {Object} update obj - * @param {Object|String|Array} optional, options or fields - * @param {Function} callback - * @return {Promise} - * @api public - */ - -Collection.prototype.updateById = function (id, obj, opts, fn) { - return this.update({ _id: id }, obj, opts, fn); -}; - -/** - * remove - * - * @param {Object} search query - * @param {Object|Function} optional, options or callback - * @param {Function} optional, callback - * @return {Promise} - */ - -Collection.prototype.remove = function (search, opts, fn) { - if ('function' == typeof opts) { - fn = opts; - opts = {}; - } - - opts = this.opts(opts); - var promise = new Promise(this, 'remove', opts); - - if (fn) { - promise.complete(fn); - } - - // cast - search = this.cast(search); - - // query - debug('%s remove %j with %j', this.name, search, opts); - promise.query = search; - this.col.remove(search, opts, promise.resolve); - - return promise; -}; - -/** - * remove by ID - * - * @param {String} hex id - * @param {Object|String|Array} optional, options or fields - * @param {Function} completion callback - * @return {Promise} - * @api public - */ - -Collection.prototype.removeById = function (id, opts, fn) { - return this.remove({ _id: id }, opts, fn); -}; - -/** - * findAndModify - * - * @param {Object} search query, or { query, update } object - * @param {Object} optional, update object - * @param {Object|String|Array} optional, options or fields - * @param {Function} callback - * @return {Promise} - * @api public - */ - -Collection.prototype.findAndModify = function (query, update, opts, fn) { - query = query || {}; - - if ('object' != typeof query.query && 'object' != typeof query.update) { - query = { - query: query - , update: update - }; - } else { - fn = opts; - opts = update; - } - - if ('string' == typeof query.query || 'function' == typeof query.query.toHexString) { - query.query = { _id: query.query }; - } - - if ('function' == typeof opts) { - fn = opts; - opts = {}; - } - - opts = opts || {}; - - // `new` defaults to `true` for upserts - if (null == opts.new && opts.upsert) { - opts.new = true; - } - - var promise = new Promise(this, 'findAndModify', opts); - - if (fn) { - promise.complete(fn); - } - - // cast - query.query = this.cast(query.query); - query.update = this.cast(query.update); - - // query - debug('%s findAndModify %j with %j', this.name, query.query, query.update); - promise.query = query; - this.col.findAndModify( - query.query - , [] - , query.update - , this.opts(opts) - , promise.resolve - ); - - return promise; -}; - -/** - * insert - * - * @param {Object} data - * @param {Object|String|Array} optional, options or fields - * @param {Function} callback - * @return {Promise} - * @api public - */ - -Collection.prototype.insert = function (data, opts, fn) { - if ('function' == typeof opts) { - fn = opts; - opts = {}; - } - - opts = this.opts(opts); - var promise = new Promise(this, 'insert', opts); - - if (fn) { - promise.complete(fn); - } - var arrayInsert = Array.isArray(data); - - // cast - data = this.cast(data); - - // query - debug('%s insert %j', this.name, data); - promise.query = data; - this.col.insert(data, opts, function (err, docs) { - immediately(function () { - var res = docs; - if (docs && !arrayInsert) { - res = docs[0]; - } - promise.resolve.call(promise, err, res); - }); - }); - - return promise; -}; - -/** - * findOne by ID - * - * @param {String} hex id - * @param {Object|String|Array} optional, options or fields - * @param {Function} completion callback - * @return {Promise} - * @api public - */ - -Collection.prototype.findById = function (id, opts, fn) { - return this.findOne({ _id: id }, opts, fn); -}; - -/** - * find - * - * @param {Object} query - * @param {Object|String|Array} optional, options or fields - * @param {Function} completion callback - * @return {Promise} - * @api public - */ - -Collection.prototype.find = function (query, opts, fn) { - if ('function' == typeof opts) { - fn = opts; - opts = {}; - } - - // cast - query = this.cast(query); - - // opts - opts = this.opts(opts); - - // query - debug('%s find %j', this.name, query); - var cursor = this.col.find(query, opts); - - // promise - var promise = new Promise(this, 'find', opts); - promise.query = query; - - if (fn) { - promise.complete(fn); - } - - if (null == opts.stream) { - immediately(function () { - if (promise.listeners('each').length) { - stream(); - } else { - cursor.toArray(promise.resolve); - } - }); - } else if (opts.stream) { - stream(); - } else { - cursor.toArray(promise.resolve); - } - - function stream () { - var didClose = false; - - cursor.each(function (err, doc) { - if (didClose && !err) { - // emit success - err = doc = null; - } - - if (err) { - promise.reject(err); - } else if (doc) { - promise.emit('each', doc); - } else { - promise.fulfill(); - } - }); - - promise.once('destroy', function(){ - didClose = true; - cursor = cursor.cursor || cursor; - cursor.close(); - }); - } - - return promise; -}; - -/** - * distinct - * - * @param {String} distinct field to select - * @param {Object} optional, query - * @param {Function} completion callback - * @return {Promise} - * @api public - */ - -Collection.prototype.distinct = function (field, query, fn) { - if ('function' == typeof query) { - fn = query; - query = {}; - } - - var promise = new Promise(this, 'distinct'); - - if (fn) { - promise.complete(fn); - } - - // cast - query = this.cast(query); - - // query - debug('%s distinct %s (%j)', this.name, field, query); - promise.query = query; - this.col.distinct(field, query, promise.resolve); - - return promise; -}; - -/** - * count - * - * @param {Object} query - * @param {Function} completion callback - * @return {Promise} - * @api public - */ - -Collection.prototype.count = function (query, fn) { - var promise = new Promise(this, 'find'); - - if (fn) { - promise.complete(fn); - } - - // cast - query = this.cast(query); - - // query - debug('%s count %j', this.name, query); - promise.query = query; - this.col.count(query, promise.resolve); - - return promise; -}; - -/** - * findOne - * - * @param {String|ObjectId|Object} query - * @param {Object} options - * @param {Function} completion callback - * @return {Promise} - * @api public - */ - -Collection.prototype.findOne = function (search, opts, fn) { - search = search || {}; - - if ('string' == typeof search || 'function' == typeof search.toHexString) { - return this.findById(search, opts, fn); - } - - if ('function' == typeof opts) { - fn = opts; - opts = {}; - } - - opts = this.opts(opts); - var promise = new Promise(this, 'findOne', opts); - - if (fn) { - promise.complete(fn); - } - - // cast - search = this.cast(search); - - // query - debug('%s findOne %j', this.name, search); - promise.query = search; - this.col.findOne(search, opts, promise.resolve); - - return promise; -}; - -/** - * Applies ObjectId casting to _id fields. - * - * @param {Object} optional, query - * @return {Object} query - * @api private - */ - -Collection.prototype.cast = function (obj) { - obj = obj || {}; - - if (obj._id) { - obj._id = this.id(obj._id); - } - - if (obj.$set && obj.$set._id) { - obj.$set._id = this.id(obj.$set._id); - } - - if (obj.$not && obj.$not._id) { - obj.$not._id = this.id(obj.$not._id); - } - - if (obj.$and && Array.isArray(obj.$and)) { - obj.$and = obj.$and.map(function (q) { - return this.cast(q); - }, this); - } - - if (obj.$or && Array.isArray(obj.$or)) { - obj.$or = obj.$or.map(function (q) { - return this.cast(q); - }, this); - } - - if (obj.$nor && Array.isArray(obj.$nor)) { - obj.$nor = obj.$nor.map(function (q) { - return this.cast(q); - }, this); - } - - return obj; -}; - -/** - * Drops the collection. - * - * @param {Function} optional, callback - * @return {Promise} - * @api public - */ - -Collection.prototype.drop = function (fn) { - var promise = new Promise(this, 'drop'); - - if (fn) { - promise.complete(fn); - } - - debug('%s drop', this.name); - promise.query = this.name; - this.col.drop(promise.resolve); - - return promise; -}; diff --git a/server/node_modules/monk/lib/manager.js b/server/node_modules/monk/lib/manager.js deleted file mode 100755 index b414c982..00000000 --- a/server/node_modules/monk/lib/manager.js +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Module dependencies. - */ - -var mongoskin = require('mongoskin') - , debug = require('debug')('monk:manager') - , Collection = require('./collection') - , ObjectId = mongoskin.ObjectID - , EventEmitter = require('events').EventEmitter - -/** - * Module exports. - */ - -module.exports = Manager; - -/** - * Manager constructor. - * - * @param {Array|String} connection uri. replica sets can be an array or - * comma-separated - * @param {Object|Function} options or connect callback - * @param {Function} connect callback - */ - -function Manager (uri, opts, fn) { - if (!uri) { - throw Error('No connection URI provided.'); - } - - if (!(this instanceof Manager)) { - return new Manager(uri, opts, fn); - } - - if ('function' == typeof opts) { - fn = opts; - opts = {}; - } - - opts = opts || {}; - opts.safe = true; - - if (Array.isArray(uri)) { - if (!opts.database) { - for (var i = 0, l = uri.length; i < l; i++) { - if (!opts.database) { - opts.database = uri[i].replace(/([^\/])+\/?/, ''); - } - uri[i] = uri[i].replace(/\/.*/, ''); - } - } - uri = uri.join(",") + "/" + opts.database; - debug('repl set connection "%j" to database "%s"', uri, opts.database); - } - - if ('string' == typeof uri) { - if ( ! /^mongodb\:\/\//.test(uri)) { - uri = 'mongodb://' + uri; - } - } - - this.driver = mongoskin.db(uri, opts); - this.helper = mongoskin.helper; - this.helper.id = ObjectId; - this.driver.open(this.onOpen.bind(this)); - this.collections = {}; - this.options = { safe: true }; - - if (fn) { - this.once('open', fn); - } -} - -/** - * Inherits from EventEmitter - */ - -Manager.prototype.__proto__ = EventEmitter.prototype; - -/** - * Open callback. - * - * @api private - */ - -Manager.prototype.onOpen = function () { - this.emit('open'); -}; - -/** - * Closes the connection. - * - * @return {Manager} for chaining - * @api private - */ - -Manager.prototype.close = function (fn) { - this.driver.close(fn); - return this; -}; - -/** - * Gets a collection. - * - * @return {Collection} collection to query against - * @api private - */ - -Manager.prototype.col = -Manager.prototype.get = function (name) { - if (!this.collections[name]) { - this.collections[name] = new Collection(this, name); - } - - return this.collections[name]; -}; - -/** - * Casts to objectid - * - * @param {Mixed} hex id or ObjectId - * @return {ObjectId} - * @api public - */ - -Manager.prototype.id = -Manager.prototype.oid = function (str) { - if (null == str) return ObjectId(); - return 'string' == typeof str ? ObjectId.createFromHexString(str) : str; -}; diff --git a/server/node_modules/monk/lib/monk.js b/server/node_modules/monk/lib/monk.js deleted file mode 100755 index b3a77e6c..00000000 --- a/server/node_modules/monk/lib/monk.js +++ /dev/null @@ -1,30 +0,0 @@ - -/** - * Module exports. - */ - -module.exports = exports = require('./manager'); - -/** - * Expose Collection. - * - * @api public - */ - -exports.Collection = require('./collection'); - -/** - * Expose Promise. - * - * @api public - */ - -exports.Promise = require('./promise'); - -/** - * Expose util. - * - * @api public - */ - -exports.util = require('./util'); diff --git a/server/node_modules/monk/lib/promise.js b/server/node_modules/monk/lib/promise.js deleted file mode 100755 index 0308250d..00000000 --- a/server/node_modules/monk/lib/promise.js +++ /dev/null @@ -1,83 +0,0 @@ - -/** - * Module dependencies. - */ - -var MPromise = require('mpromise'); -var immediately = global.setImmediate || process.nextTick; - -/** - * Module exports. - */ - -module.exports = Promise; - -/** - * Promise constructor. - * - * @param {Collection} collection - * @param {String} type - * @param {Object} query options - * @api public - */ - -function Promise (col, type, opts) { - this.col = col; - this.type = type; - this.opts = opts || {}; - - // MPromise constructor - MPromise.call(this); - - // Compability methods - this.success = this.onFulfill; - this.error = this.onReject; - this.complete = this.onResolve; - this.onResolve(this.emit.bind(this,'complete')); - - // for practical purposes - this.resolve = MPromise.prototype.resolve.bind(this); - this.fulfill = MPromise.prototype.fulfill.bind(this); - this.reject = MPromise.prototype.reject.bind(this); -} - -/*! - * event names - */ - -Promise.SUCCESS = 'success'; -Promise.FAILURE = 'error'; - -/** - * Inherits from MPromise. - */ - -Promise.prototype.__proto__ = MPromise.prototype; - -/** - * Each method - * - * @api public - */ - -Promise.prototype.each = function (fn) { - if (fn) { - this.on('each', fn); - } - return this; -}; - -/** - * Destroys the promise. - * - * @api public - */ - -Promise.prototype.destroy = function(){ - this.emit('destroy'); - var self = this; - immediately(function(){ - // null the query ref - delete self.query; - }); -}; diff --git a/server/node_modules/monk/lib/util.js b/server/node_modules/monk/lib/util.js deleted file mode 100755 index 0bdeb5af..00000000 --- a/server/node_modules/monk/lib/util.js +++ /dev/null @@ -1,44 +0,0 @@ - -/** - * Parses all the possible ways of expressing fields. - * - * @param {String|Object|Array} fields - * @return {Object} fields in object format - * @api public - */ - -exports.fields = function (obj) { - if (!Array.isArray(obj) && 'object' == typeof obj) { - return obj; - } - - var fields = {}; - obj = 'string' == typeof obj ? obj.split(' ') : (obj || []); - - for (var i = 0, l = obj.length; i < l; i++) { - if ('-' == obj[i][0]) { - fields[obj[i].substr(1)] = 0; - } else { - fields[obj[i]] = 1; - } - } - - return fields; -}; - -/** - * Parses an object format. - * - * @param {String|Array|Object} fields or options - * @return {Object} options - * @api public - */ - -exports.options = function (opts) { - if ('string' == typeof opts || Array.isArray(opts)) { - return { fields: exports.fields(opts) }; - } - opts = opts || {}; - opts.fields = exports.fields(opts.fields); - return opts; -}; diff --git a/server/node_modules/monk/node_modules/debug/.jshintrc b/server/node_modules/monk/node_modules/debug/.jshintrc deleted file mode 100755 index 299877f2..00000000 --- a/server/node_modules/monk/node_modules/debug/.jshintrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "laxbreak": true -} diff --git a/server/node_modules/monk/node_modules/debug/.npmignore b/server/node_modules/monk/node_modules/debug/.npmignore deleted file mode 100755 index 7e6163db..00000000 --- a/server/node_modules/monk/node_modules/debug/.npmignore +++ /dev/null @@ -1,6 +0,0 @@ -support -test -examples -example -*.sock -dist diff --git a/server/node_modules/monk/node_modules/debug/History.md b/server/node_modules/monk/node_modules/debug/History.md deleted file mode 100755 index 770e4832..00000000 --- a/server/node_modules/monk/node_modules/debug/History.md +++ /dev/null @@ -1,186 +0,0 @@ - -2.1.3 / 2015-03-13 -================== - - * Updated stdout/stderr example (#186) - * Updated example/stdout.js to match debug current behaviour - * Renamed example/stderr.js to stdout.js - * Update Readme.md (#184) - * replace high intensity foreground color for bold (#182, #183) - -2.1.2 / 2015-03-01 -================== - - * dist: recompile - * update "ms" to v0.7.0 - * package: update "browserify" to v9.0.3 - * component: fix "ms.js" repo location - * changed bower package name - * updated documentation about using debug in a browser - * fix: security error on safari (#167, #168, @yields) - -2.1.1 / 2014-12-29 -================== - - * browser: use `typeof` to check for `console` existence - * browser: check for `console.log` truthiness (fix IE 8/9) - * browser: add support for Chrome apps - * Readme: added Windows usage remarks - * Add `bower.json` to properly support bower install - -2.1.0 / 2014-10-15 -================== - - * node: implement `DEBUG_FD` env variable support - * package: update "browserify" to v6.1.0 - * package: add "license" field to package.json (#135, @panuhorsmalahti) - -2.0.0 / 2014-09-01 -================== - - * package: update "browserify" to v5.11.0 - * node: use stderr rather than stdout for logging (#29, @stephenmathieson) - -1.0.4 / 2014-07-15 -================== - - * dist: recompile - * example: remove `console.info()` log usage - * example: add "Content-Type" UTF-8 header to browser example - * browser: place %c marker after the space character - * browser: reset the "content" color via `color: inherit` - * browser: add colors support for Firefox >= v31 - * debug: prefer an instance `log()` function over the global one (#119) - * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) - -1.0.3 / 2014-07-09 -================== - - * Add support for multiple wildcards in namespaces (#122, @seegno) - * browser: fix lint - -1.0.2 / 2014-06-10 -================== - - * browser: update color palette (#113, @gscottolson) - * common: make console logging function configurable (#108, @timoxley) - * node: fix %o colors on old node <= 0.8.x - * Makefile: find node path using shell/which (#109, @timoxley) - -1.0.1 / 2014-06-06 -================== - - * browser: use `removeItem()` to clear localStorage - * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) - * package: add "contributors" section - * node: fix comment typo - * README: list authors - -1.0.0 / 2014-06-04 -================== - - * make ms diff be global, not be scope - * debug: ignore empty strings in enable() - * node: make DEBUG_COLORS able to disable coloring - * *: export the `colors` array - * npmignore: don't publish the `dist` dir - * Makefile: refactor to use browserify - * package: add "browserify" as a dev dependency - * Readme: add Web Inspector Colors section - * node: reset terminal color for the debug content - * node: map "%o" to `util.inspect()` - * browser: map "%j" to `JSON.stringify()` - * debug: add custom "formatters" - * debug: use "ms" module for humanizing the diff - * Readme: add "bash" syntax highlighting - * browser: add Firebug color support - * browser: add colors for WebKit browsers - * node: apply log to `console` - * rewrite: abstract common logic for Node & browsers - * add .jshintrc file - -0.8.1 / 2014-04-14 -================== - - * package: re-add the "component" section - -0.8.0 / 2014-03-30 -================== - - * add `enable()` method for nodejs. Closes #27 - * change from stderr to stdout - * remove unnecessary index.js file - -0.7.4 / 2013-11-13 -================== - - * remove "browserify" key from package.json (fixes something in browserify) - -0.7.3 / 2013-10-30 -================== - - * fix: catch localStorage security error when cookies are blocked (Chrome) - * add debug(err) support. Closes #46 - * add .browser prop to package.json. Closes #42 - -0.7.2 / 2013-02-06 -================== - - * fix package.json - * fix: Mobile Safari (private mode) is broken with debug - * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript - -0.7.1 / 2013-02-05 -================== - - * add repository URL to package.json - * add DEBUG_COLORED to force colored output - * add browserify support - * fix component. Closes #24 - -0.7.0 / 2012-05-04 -================== - - * Added .component to package.json - * Added debug.component.js build - -0.6.0 / 2012-03-16 -================== - - * Added support for "-" prefix in DEBUG [Vinay Pulim] - * Added `.enabled` flag to the node version [TooTallNate] - -0.5.0 / 2012-02-02 -================== - - * Added: humanize diffs. Closes #8 - * Added `debug.disable()` to the CS variant - * Removed padding. Closes #10 - * Fixed: persist client-side variant again. Closes #9 - -0.4.0 / 2012-02-01 -================== - - * Added browser variant support for older browsers [TooTallNate] - * Added `debug.enable('project:*')` to browser variant [TooTallNate] - * Added padding to diff (moved it to the right) - -0.3.0 / 2012-01-26 -================== - - * Added millisecond diff when isatty, otherwise UTC string - -0.2.0 / 2012-01-22 -================== - - * Added wildcard support - -0.1.0 / 2011-12-02 -================== - - * Added: remove colors unless stderr isatty [TooTallNate] - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/server/node_modules/monk/node_modules/debug/Makefile b/server/node_modules/monk/node_modules/debug/Makefile deleted file mode 100755 index b0bde6e6..00000000 --- a/server/node_modules/monk/node_modules/debug/Makefile +++ /dev/null @@ -1,33 +0,0 @@ - -# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 -THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) -THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) - -# BIN directory -BIN := $(THIS_DIR)/node_modules/.bin - -# applications -NODE ?= $(shell which node) -NPM ?= $(NODE) $(shell which npm) -BROWSERIFY ?= $(NODE) $(BIN)/browserify - -all: dist/debug.js - -install: node_modules - -clean: - @rm -rf node_modules dist - -dist: - @mkdir -p $@ - -dist/debug.js: node_modules browser.js debug.js dist - @$(BROWSERIFY) \ - --standalone debug \ - . > $@ - -node_modules: package.json - @NODE_ENV= $(NPM) install - @touch node_modules - -.PHONY: all install clean diff --git a/server/node_modules/monk/node_modules/debug/Readme.md b/server/node_modules/monk/node_modules/debug/Readme.md deleted file mode 100755 index 14222e0c..00000000 --- a/server/node_modules/monk/node_modules/debug/Readme.md +++ /dev/null @@ -1,178 +0,0 @@ -# debug - - tiny node.js debugging utility modelled after node core's debugging technique. - -## Installation - -```bash -$ npm install debug -``` - -## Usage - - With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. - -Example _app.js_: - -```js -var debug = require('debug')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %s', name); - -http.createServer(function(req, res){ - debug(req.method + ' ' + req.url); - res.end('hello\n'); -}).listen(3000, function(){ - debug('listening'); -}); - -// fake worker of some kind - -require('./worker'); -``` - -Example _worker.js_: - -```js -var debug = require('debug')('worker'); - -setInterval(function(){ - debug('doing some work'); -}, 1000); -``` - - The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: - - ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) - - ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) - -#### Windows note - - On Windows the environment variable is set using the `set` command. - - ```cmd - set DEBUG=*,-not_this - ``` - -Then, run the program to be debugged as usual. - -## Millisecond diff - - When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. - - ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) - - When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: - - ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) - -## Conventions - - If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". - -## Wildcards - - The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. - - You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". - -## Browser support - - Debug works in the browser as well, currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. Somewhere in the code on your page, include: - -```js -window.myDebug = require("debug"); -``` - - ("debug" is a global object in the browser so we give this object a different name.) When your page is open in the browser, type the following in the console: - -```js -myDebug.enable("worker:*") -``` - - Refresh the page. Debug output will continue to be sent to the console until it is disabled by typing `myDebug.disable()` in the console. - -```js -a = debug('worker:a'); -b = debug('worker:b'); - -setInterval(function(){ - a('doing some work'); -}, 1000); - -setInterval(function(){ - b('doing some work'); -}, 1200); -``` - -#### Web Inspector Colors - - Colors are also enabled on "Web Inspectors" that understand the `%c` formatting - option. These are WebKit web inspectors, Firefox ([since version - 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) - and the Firebug plugin for Firefox (any version). - - Colored output looks something like: - - ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) - -### stderr vs stdout - -You can set an alternative logging method per-namespace by overriding the `log` method on a per-namespace or globally: - -Example _stdout.js_: - -```js -var debug = require('debug'); -var error = debug('app:error'); - -// by default stderr is used -error('goes to stderr!'); - -var log = debug('app:log'); -// set this namespace to log via console.log -log.log = console.log.bind(console); // don't forget to bind to console! -log('goes to stdout'); -error('still goes to stderr!'); - -// set all output to go via console.info -// overrides all per-namespace log settings -debug.log = console.info.bind(console); -error('now goes to stdout via console.info'); -log('still goes to stdout, but via console.info now'); -``` - -## Authors - - - TJ Holowaychuk - - Nathan Rajlich - -## License - -(The MIT License) - -Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/monk/node_modules/debug/bower.json b/server/node_modules/monk/node_modules/debug/bower.json deleted file mode 100755 index f7d3f6dc..00000000 --- a/server/node_modules/monk/node_modules/debug/bower.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "visionmedia-debug", - "main": "dist/debug.js", - "version": "2.1.3", - "homepage": "https://github.com/visionmedia/debug", - "authors": [ - "TJ Holowaychuk " - ], - "description": "visionmedia-debug", - "moduleType": [ - "amd", - "es6", - "globals", - "node" - ], - "keywords": [ - "visionmedia", - "debug" - ], - "license": "MIT", - "ignore": [ - "**/.*", - "node_modules", - "bower_components", - "test", - "tests" - ] -} diff --git a/server/node_modules/monk/node_modules/debug/browser.js b/server/node_modules/monk/node_modules/debug/browser.js deleted file mode 100755 index 55f4cf92..00000000 --- a/server/node_modules/monk/node_modules/debug/browser.js +++ /dev/null @@ -1,175 +0,0 @@ - -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; - -/** - * Use chrome.storage.local if we are in an app - */ - -var storage; - -if (typeof chrome !== 'undefined' && typeof chrome.storage !== 'undefined') - storage = chrome.storage.local; -else - storage = localstorage(); - -/** - * Colors. - */ - -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -function useColors() { - // is webkit? http://stackoverflow.com/a/16459606/376773 - return ('WebkitAppearance' in document.documentElement.style) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (window.console && (console.firebug || (console.exception && console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - return JSON.stringify(v); -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs() { - var args = arguments; - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return args; - - var c = 'color: ' + this.color; - args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); - return args; -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - storage.removeItem('debug'); - } else { - storage.debug = namespaces; - } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = storage.debug; - } catch(e) {} - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage(){ - try { - return window.localStorage; - } catch (e) {} -} diff --git a/server/node_modules/monk/node_modules/debug/component.json b/server/node_modules/monk/node_modules/debug/component.json deleted file mode 100755 index 52ffd422..00000000 --- a/server/node_modules/monk/node_modules/debug/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "debug", - "repo": "visionmedia/debug", - "description": "small debugging utility", - "version": "2.1.3", - "keywords": [ - "debug", - "log", - "debugger" - ], - "main": "browser.js", - "scripts": [ - "browser.js", - "debug.js" - ], - "dependencies": { - "rauchg/ms.js": "0.7.0" - } -} diff --git a/server/node_modules/monk/node_modules/debug/debug.js b/server/node_modules/monk/node_modules/debug/debug.js deleted file mode 100755 index 7571a860..00000000 --- a/server/node_modules/monk/node_modules/debug/debug.js +++ /dev/null @@ -1,197 +0,0 @@ - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = debug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; - -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lowercased letter, i.e. "n". - */ - -exports.formatters = {}; - -/** - * Previously assigned color. - */ - -var prevColor = 0; - -/** - * Previous log timestamp. - */ - -var prevTime; - -/** - * Select a color. - * - * @return {Number} - * @api private - */ - -function selectColor() { - return exports.colors[prevColor++ % exports.colors.length]; -} - -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function debug(namespace) { - - // define the `disabled` version - function disabled() { - } - disabled.enabled = false; - - // define the `enabled` version - function enabled() { - - var self = enabled; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // add the `color` if not set - if (null == self.useColors) self.useColors = exports.useColors(); - if (null == self.color && self.useColors) self.color = selectColor(); - - var args = Array.prototype.slice.call(arguments); - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %o - args = ['%o'].concat(args); - } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - if ('function' === typeof exports.formatArgs) { - args = exports.formatArgs.apply(self, args); - } - var logFn = enabled.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - enabled.enabled = true; - - var fn = exports.enabled(namespace) ? enabled : disabled; - - fn.namespace = namespace; - - return fn; -} - -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - var split = (namespaces || '').split(/[\s,]+/); - var len = split.length; - - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } -} - -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} - -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} diff --git a/server/node_modules/monk/node_modules/debug/node.js b/server/node_modules/monk/node_modules/debug/node.js deleted file mode 100755 index 1d392a81..00000000 --- a/server/node_modules/monk/node_modules/debug/node.js +++ /dev/null @@ -1,209 +0,0 @@ - -/** - * Module dependencies. - */ - -var tty = require('tty'); -var util = require('util'); - -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -/** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log - */ - -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase(); - if (0 === debugColors.length) { - return tty.isatty(fd); - } else { - return '0' !== debugColors - && 'no' !== debugColors - && 'false' !== debugColors - && 'disabled' !== debugColors; - } -} - -/** - * Map %o to `util.inspect()`, since Node doesn't do that out of the box. - */ - -var inspect = (4 === util.inspect.length ? - // node <= 0.8.x - function (v, colors) { - return util.inspect(v, void 0, void 0, colors); - } : - // node > 0.8.x - function (v, colors) { - return util.inspect(v, { colors: colors }); - } -); - -exports.formatters.o = function(v) { - return inspect(v, this.useColors) - .replace(/\s*\n\s*/g, ' '); -}; - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs() { - var args = arguments; - var useColors = this.useColors; - var name = this.namespace; - - if (useColors) { - var c = this.color; - - args[0] = ' \u001b[3' + c + ';1m' + name + ' ' - + '\u001b[0m' - + args[0] + '\u001b[3' + c + 'm' - + ' +' + exports.humanize(this.diff) + '\u001b[0m'; - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; - } - return args; -} - -/** - * Invokes `console.error()` with the specified arguments. - */ - -function log() { - return stream.write(util.format.apply(this, arguments) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Copied from `node/src/node.js`. - * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. - */ - -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); - - // Note stream._type is used for test-module-load-list.js - - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; - - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - - case 'FILE': - var fs = require('fs'); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; - - case 'PIPE': - case 'TCP': - var net = require('net'); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); - - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; - - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } - - // For supporting legacy API we put the FD here. - stream.fd = fd; - - stream._isStdio = true; - - return stream; -} - -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ - -exports.enable(load()); diff --git a/server/node_modules/monk/node_modules/debug/node_modules/ms/.npmignore b/server/node_modules/monk/node_modules/debug/node_modules/ms/.npmignore deleted file mode 100755 index d1aa0ce4..00000000 --- a/server/node_modules/monk/node_modules/debug/node_modules/ms/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -node_modules -test -History.md -Makefile -component.json diff --git a/server/node_modules/monk/node_modules/debug/node_modules/ms/LICENSE b/server/node_modules/monk/node_modules/debug/node_modules/ms/LICENSE deleted file mode 100755 index 6c07561b..00000000 --- a/server/node_modules/monk/node_modules/debug/node_modules/ms/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 Guillermo Rauch - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/monk/node_modules/debug/node_modules/ms/README.md b/server/node_modules/monk/node_modules/debug/node_modules/ms/README.md deleted file mode 100755 index 0fd54fdc..00000000 --- a/server/node_modules/monk/node_modules/debug/node_modules/ms/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# ms.js: miliseconds conversion utility - -```js -ms('2 days') // 172800000 -ms('1d') // 86400000 -ms('10h') // 36000000 -ms('2.5 hrs') // 9000000 -ms('2h') // 7200000 -ms('1m') // 60000 -ms('5s') // 5000 -ms('100') // 100 -``` - -```js -ms(60000) // "1m" -ms(2 * 60000) // "2m" -ms(ms('10 hours')) // "10h" -``` - -```js -ms(60000, { long: true }) // "1 minute" -ms(2 * 60000, { long: true }) // "2 minutes" -ms(ms('10 hours'), { long: true }) // "10 hours" -``` - -- Node/Browser compatible. Published as [`ms`](https://www.npmjs.org/package/ms) in [NPM](nodejs.org/download). -- If a number is supplied to `ms`, a string with a unit is returned. -- If a string that contains the number is supplied, it returns it as -a number (e.g: it returns `100` for `'100'`). -- If you pass a string with a number and a valid unit, the number of -equivalent ms is returned. - -## License - -MIT diff --git a/server/node_modules/monk/node_modules/debug/node_modules/ms/index.js b/server/node_modules/monk/node_modules/debug/node_modules/ms/index.js deleted file mode 100755 index e79bfa18..00000000 --- a/server/node_modules/monk/node_modules/debug/node_modules/ms/index.js +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} options - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options){ - options = options || {}; - if ('string' == typeof val) return parse(val); - return options.long - ? long(val) - : short(val); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); - if (!match) return; - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function short(ms) { - if (ms >= d) return Math.round(ms / d) + 'd'; - if (ms >= h) return Math.round(ms / h) + 'h'; - if (ms >= m) return Math.round(ms / m) + 'm'; - if (ms >= s) return Math.round(ms / s) + 's'; - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function long(ms) { - return plural(ms, d, 'day') - || plural(ms, h, 'hour') - || plural(ms, m, 'minute') - || plural(ms, s, 'second') - || ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) return; - if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; - return Math.ceil(ms / n) + ' ' + name + 's'; -} diff --git a/server/node_modules/monk/node_modules/debug/node_modules/ms/package.json b/server/node_modules/monk/node_modules/debug/node_modules/ms/package.json deleted file mode 100755 index ec3ea9b0..00000000 --- a/server/node_modules/monk/node_modules/debug/node_modules/ms/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "ms", - "version": "0.7.0", - "description": "Tiny ms conversion utility", - "repository": { - "type": "git", - "url": "git://github.com/guille/ms.js.git" - }, - "main": "./index", - "devDependencies": { - "mocha": "*", - "expect.js": "*", - "serve": "*" - }, - "component": { - "scripts": { - "ms/index.js": "index.js" - } - }, - "gitHead": "1e9cd9b05ef0dc26f765434d2bfee42394376e52", - "bugs": { - "url": "https://github.com/guille/ms.js/issues" - }, - "homepage": "https://github.com/guille/ms.js", - "_id": "ms@0.7.0", - "scripts": {}, - "_shasum": "865be94c2e7397ad8a57da6a633a6e2f30798b83", - "_from": "ms@0.7.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "rauchg", - "email": "rauchg@gmail.com" - }, - "maintainers": [ - { - "name": "rauchg", - "email": "rauchg@gmail.com" - } - ], - "dist": { - "shasum": "865be94c2e7397ad8a57da6a633a6e2f30798b83", - "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.0.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.0.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/server/node_modules/monk/node_modules/debug/package.json b/server/node_modules/monk/node_modules/debug/package.json deleted file mode 100755 index a870a5b8..00000000 --- a/server/node_modules/monk/node_modules/debug/package.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "name": "debug", - "version": "2.1.3", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/debug.git" - }, - "description": "small debugging utility", - "keywords": [ - "debug", - "log", - "debugger" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "contributors": [ - { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "http://n8.io" - } - ], - "license": "MIT", - "dependencies": { - "ms": "0.7.0" - }, - "devDependencies": { - "browserify": "9.0.3", - "mocha": "*" - }, - "main": "./node.js", - "browser": "./browser.js", - "component": { - "scripts": { - "debug/index.js": "browser.js", - "debug/debug.js": "debug.js" - } - }, - "gitHead": "0a8e4b7e0d2d1b55ef4e7422498ca24c677ae63a", - "bugs": { - "url": "https://github.com/visionmedia/debug/issues" - }, - "homepage": "https://github.com/visionmedia/debug", - "_id": "debug@2.1.3", - "scripts": {}, - "_shasum": "ce8ab1b5ee8fbee2bfa3b633cab93d366b63418e", - "_from": "debug@*", - "_npmVersion": "2.5.1", - "_nodeVersion": "0.12.0", - "_npmUser": { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - } - ], - "dist": { - "shasum": "ce8ab1b5ee8fbee2bfa3b633cab93d366b63418e", - "tarball": "http://registry.npmjs.org/debug/-/debug-2.1.3.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/debug/-/debug-2.1.3.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/server/node_modules/monk/node_modules/mongodb/.gitmodules b/server/node_modules/monk/node_modules/mongodb/.gitmodules deleted file mode 100755 index e69de29b..00000000 diff --git a/server/node_modules/monk/node_modules/mongodb/.travis.yml b/server/node_modules/monk/node_modules/mongodb/.travis.yml deleted file mode 100755 index bdb4101e..00000000 --- a/server/node_modules/monk/node_modules/mongodb/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: node_js -node_js: - - 0.10 - - 0.11 -sudo: false -env: - - MONGODB_VERSION=2.2.x - - MONGODB_VERSION=2.4.x - - MONGODB_VERSION=2.6.x - - MONGODB_VERSION=3.0.x \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/CONTRIBUTING.md b/server/node_modules/monk/node_modules/mongodb/CONTRIBUTING.md deleted file mode 100755 index c23e426c..00000000 --- a/server/node_modules/monk/node_modules/mongodb/CONTRIBUTING.md +++ /dev/null @@ -1,23 +0,0 @@ -## Contributing to the driver - -### Bugfixes - -- Before starting to write code, look for existing [tickets](https://jira.mongodb.org/browse/NODE) or [create one](https://jira.mongodb.org/secure/CreateIssue!default.jspa) for your specific issue under the "Node Driver" project. That way you avoid working on something that might not be of interest or that has been addressed already in a different branch. -- Fork the [repo](https://github.com/mongodb/node-mongodb-native) _or_ for small documentation changes, navigate to the source on github and click the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button. -- Follow the general coding style of the rest of the project: - - 2 space tabs - - no trailing whitespace - - comma last - - inline documentation for new methods, class members, etc - - 0 space between conditionals/functions, and their parenthesis and curly braces - - `if(..) {` - - `for(..) {` - - `while(..) {` - - `function(err) {` -- Write tests and make sure they pass (execute `npm test` from the cmd line to run the test suite). - -### Documentation - -To contribute to the [API documentation](http://mongodb.github.com/node-mongodb-native/) just make your changes to the inline documentation of the appropriate [source code](https://github.com/mongodb/node-mongodb-native/tree/master/docs) in the master branch and submit a [pull request](https://help.github.com/articles/using-pull-requests/). You might also use the github [Edit](https://github.com/blog/844-forking-with-the-edit-button) button. - -If you'd like to preview your documentation changes, first commit your changes to your local master branch, then execute `make generate_docs`. Make sure you have the python documentation framework sphinx installed `easy_install sphinx`. The docs are generated under `docs/build'. If all looks good, submit a [pull request](https://help.github.com/articles/using-pull-requests/) to the master branch with your changes. diff --git a/server/node_modules/monk/node_modules/mongodb/LICENSE b/server/node_modules/monk/node_modules/mongodb/LICENSE deleted file mode 100755 index 261eeb9e..00000000 --- a/server/node_modules/monk/node_modules/mongodb/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/server/node_modules/monk/node_modules/mongodb/Makefile b/server/node_modules/monk/node_modules/mongodb/Makefile deleted file mode 100755 index 59d2bfeb..00000000 --- a/server/node_modules/monk/node_modules/mongodb/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -NODE = node -NPM = npm -NODEUNIT = node_modules/nodeunit/bin/nodeunit -DOX = node_modules/dox/bin/dox -name = all - -total: build_native - -test_functional: - node test/runner.js -t functional - -test_ssl: - node test/runner.js -t ssl - -test_replicaset: - node test/runner.js -t replicaset - -test_sharded: - node test/runner.js -t sharded - -test_auth: - node test/runner.js -t auth - -generate_docs: - $(NODE) dev/tools/build-docs.js - make --directory=./docs/sphinx-docs --file=Makefile html - -.PHONY: total diff --git a/server/node_modules/monk/node_modules/mongodb/Readme.md b/server/node_modules/monk/node_modules/mongodb/Readme.md deleted file mode 100755 index 5e4877df..00000000 --- a/server/node_modules/monk/node_modules/mongodb/Readme.md +++ /dev/null @@ -1,418 +0,0 @@ -## MongoDB Node.JS Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native/ | -| apidoc | http://mongodb.github.io/node-mongodb-native/ | -| source | https://github.com/mongodb/node-mongodb-native | -| mongodb | http://www.mongodb.org/ | - -### Blogs of Engineers involved in the driver -- Christian Kvalheim [@christkv](https://twitter.com/christkv) -- Valeri Karpov [@code_barbarian](https://twitter.com/code_barbarian) - -### Bugs / Feature Requests - -Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a -case in our issue management tool, JIRA: - -- Create an account and login . -- Navigate to the NODE project . -- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the -Core Server (i.e. SERVER) project are **public**. - -### Questions and Bug Reports - - * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native - * jira: http://jira.mongodb.org/ - -### Change Log - -http://jira.mongodb.org/browse/NODE - -## Install - -To install the most recent release from npm, run: - - npm install mongodb - -That may give you a warning telling you that bugs['web'] should be bugs['url'], it would be safe to ignore it (this has been fixed in the development version) - -To install the latest from the repository, run:: - - npm install path/to/node-mongodb-native - -## Live Examples - - -## Introduction - -This is a node.js driver for MongoDB. It's a port (or close to a port) of the library for ruby at http://github.com/mongodb/mongo-ruby-driver/. - -A simple example of inserting a document. - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - var collection = db.collection('test_insert'); - collection.insert({a:2}, function(err, docs) { - - collection.count(function(err, count) { - console.log(format("count = %s", count)); - }); - - // Locate all the entries using find - collection.find().toArray(function(err, results) { - console.dir(results); - // Let's close the db - db.close(); - }); - }); - }) -``` - -## Data types - -To store and retrieve the non-JSON MongoDb primitives ([ObjectID](http://www.mongodb.org/display/DOCS/Object+IDs), Long, Binary, [Timestamp](http://www.mongodb.org/display/DOCS/Timestamp+data+type), [DBRef](http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef), Code). - -In particular, every document has a unique `_id` which can be almost any type, and by default a 12-byte ObjectID is created. ObjectIDs can be represented as 24-digit hexadecimal strings, but you must convert the string back into an ObjectID before you can use it in the database. For example: - -```javascript - // Get the objectID type - var ObjectID = require('mongodb').ObjectID; - - var idString = '4e4e1638c85e808431000003'; - collection.findOne({_id: new ObjectID(idString)}, console.log) // ok - collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined -``` - -Here are the constructors the non-Javascript BSON primitive types: - -```javascript - // Fetch the library - var mongo = require('mongodb'); - // Create new instances of BSON types - new mongo.Long(numberString) - new mongo.ObjectID(hexString) - new mongo.Timestamp() // the actual unique number is generated on insert. - new mongo.DBRef(collectionName, id, dbName) - new mongo.Binary(buffer) // takes a string or Buffer - new mongo.Code(code, [context]) - new mongo.Symbol(string) - new mongo.MinKey() - new mongo.MaxKey() - new mongo.Double(number) // Force double storage -``` - -### The C/C++ bson parser/serializer - -If you are running a version of this library has the C/C++ parser compiled, to enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below - -```javascript - // using native_parser: - MongoClient.connect('mongodb://127.0.0.1:27017/test' - , {db: {native_parser: true}}, function(err, db) {}) -``` - -The C++ parser uses the js objects both for serialization and deserialization. - -## GitHub information - -The source code is available at http://github.com/mongodb/node-mongodb-native. -You can either clone the repository or download a tarball of the latest release. - -Once you have the source you can test the driver by running - - $ node test/runner.js -t functional - -in the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass. - -## Examples - -For examples look in the examples/ directory. You can execute the examples using node. - - $ cd examples - $ node queries.js - -## GridStore - -The GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition. - -For more information have a look at [Gridstore](https://github.com/mongodb/node-mongodb-native/blob/master/docs/gridfs.md) - -## Replicasets - -For more information about how to connect to a replicaset have a look at the extensive documentation [Documentation](http://mongodb.github.com/node-mongodb-native/) - -### Primary Key Factories - -Defining your own primary key factory allows you to generate your own series of id's -(this could f.ex be to use something like ISBN numbers). The generated the id needs to be a 12 byte long "string". - -Simple example below - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - // Custom factory (need to provide a 12 byte array); - CustomPKFactory = function() {} - CustomPKFactory.prototype = new Object(); - CustomPKFactory.createPk = function() { - return new ObjectID("aaaaaaaaaaaa"); - } - - MongoClient.connect('mongodb://127.0.0.1:27017/test', {'pkFactory':CustomPKFactory}, function(err, db) { - if(err) throw err; - - db.dropDatabase(function(err, done) { - - db.createCollection('test_custom_key', function(err, collection) { - - collection.insert({'a':1}, function(err, docs) { - - collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}).toArray(function(err, items) { - console.dir(items); - // Let's close the db - db.close(); - }); - }); - }); - }); - }); -``` - -## Documentation - -If this document doesn't answer your questions, see the source of -[Collection](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js) -or [Cursor](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/cursor.js), -or the documentation at MongoDB for query and update formats. - -### Find - -The find method is actually a factory method to create -Cursor objects. A Cursor lazily uses the connection the first time -you call `nextObject`, `each`, or `toArray`. - -The basic operation on a cursor is the `nextObject` method -that fetches the next matching document from the database. The convenience -methods `each` and `toArray` call `nextObject` until the cursor is exhausted. - -Signatures: - -```javascript - var cursor = collection.find(query, [fields], options); - cursor.sort(fields).limit(n).skip(m). - - cursor.nextObject(function(err, doc) {}); - cursor.each(function(err, doc) {}); - cursor.toArray(function(err, docs) {}); - - cursor.rewind() // reset the cursor to its initial state. -``` - -Useful chainable methods of cursor. These can optionally be options of `find` instead of method calls: - - * `.limit(n).skip(m)` to control paging. - * `.sort(fields)` Order by the given fields. There are several equivalent syntaxes: - * `.sort({field1: -1, field2: 1})` descending by field1, then ascending by field2. - * `.sort([['field1', 'desc'], ['field2', 'asc']])` same as above - * `.sort([['field1', 'desc'], 'field2'])` same as above - * `.sort('field1')` ascending by field1 - -Other options of `find`: - -* `fields` the fields to fetch (to avoid transferring the entire document) -* `tailable` if true, makes the cursor [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors). -* `batchSize` The number of the subset of results to request the database -to return for every request. This should initially be greater than 1 otherwise -the database will automatically close the cursor. The batch size can be set to 1 -with `batchSize(n, function(err){})` after performing the initial query to the database. -* `hint` See [Optimization: hint](http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint). -* `explain` turns this into an explain query. You can also call -`explain()` on any cursor to fetch the explanation. -* `snapshot` prevents documents that are updated while the query is active -from being returned multiple times. See more -[details about query snapshots](http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database). -* `timeout` if false, asks MongoDb not to time out this cursor after an -inactivity period. - -For information on how to create queries, see the -[MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying). - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - var collection = db - .collection('test') - .find({}) - .limit(10) - .toArray(function(err, docs) { - console.dir(docs); - }); - }); -``` - -### Insert - -Signature: - -```javascript - collection.insert(docs, options, [callback]); -``` - -where `docs` can be a single document or an array of documents. - -Useful options: - -* `w:1` Should always set if you have a callback. - -See also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting). - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - db.collection('test').insert({hello: 'world'}, {w:1}, function(err, objects) { - if (err) console.warn(err.message); - if (err && err.message.indexOf('E11000 ') !== -1) { - // this _id was already inserted in the database - } - }); - }); -``` - -Note that there's no reason to pass a callback to the insert or update commands -unless you use the `w:1` option. If you don't specify `w:1`, then -your callback will be called immediately. - -### Update: update and insert (upsert) - -The update operation will update the first document that matches your query -(or all documents that match if you use `multi:true`). -If `w:1`, `upsert` is not set, and no documents match, your callback will return 0 documents updated. - -See the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for -the modifier (`$inc`, `$set`, `$push`, etc.) formats. - -Signature: - -```javascript - collection.update(criteria, objNew, options, [callback]); -``` - -Useful options: - -* `w:1` Should always set if you have a callback. -* `multi:true` If set, all matching documents are updated, not just the first. -* `upsert:true` Atomically inserts the document if no documents matched. - -Example for `update`: - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - db.collection('test').update({hi: 'here'}, {$set: {hi: 'there'}}, {w:1}, function(err) { - if (err) console.warn(err.message); - else console.log('successfully updated'); - }); - }); -``` - -### Find and modify - -`findAndModify` is like `update`, but it also gives the updated document to -your callback. But there are a few key differences between findAndModify and -update: - - 1. The signatures differ. - 2. You can only findAndModify a single item, not multiple items. - -Signature: - -```javascript - collection.findAndModify(query, sort, update, options, callback) -``` - -The sort parameter is used to specify which object to operate on, if more than -one document matches. It takes the same format as the cursor sort (see -Connection.find above). - -See the -[MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) -for more details. - -Useful options: - -* `remove:true` set to a true to remove the object before returning -* `new:true` set to true if you want to return the modified object rather than the original. Ignored for remove. -* `upsert:true` Atomically inserts the document if no documents matched. - -Example for `findAndModify`: - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - db.collection('test').findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {}, function(err, object) { - if (err) console.warn(err.message); - else console.dir(object); // undefined if no matching object exists. - }); - }); -``` - -### Save - -The `save` method is a shorthand for upsert if the document contains an -`_id`, or an insert if there is no `_id`. - -## Release Notes - -See HISTORY - -## Credits - -1. [10gen](http://github.com/mongodb/mongo-ruby-driver/) -2. [Google Closure Library](http://code.google.com/closure/library/) -3. [Jonas Raoni Soares Silva](http://jsfromhell.com/classes/binary-parser) - -## Contributors - -Aaron Heckmann, Christoph Pojer, Pau Ramon Revilla, Nathan White, Emmerman, Seth LaForge, Boris Filipov, Stefan Schärmeli, Tedde Lundgren, renctan, Sergey Ukustov, Ciaran Jessup, kuno, srimonti, Erik Abele, Pratik Daga, Slobodan Utvic, Kristina Chodorow, Yonathan Randolph, Brian Noguchi, Sam Epstein, James Harrison Fisher, Vladimir Dronnikov, Ben Hockey, Henrik Johansson, Simon Weare, Alex Gorbatchev, Shimon Doodkin, Kyle Mueller, Eran Hammer-Lahav, Marcin Ciszak, François de Metz, Vinay Pulim, nstielau, Adam Wiggins, entrinzikyl, Jeremy Selier, Ian Millington, Public Keating, andrewjstone, Christopher Stott, Corey Jewett, brettkiefer, Rob Holland, Senmiao Liu, heroic, gitfy - -## License - - Copyright 2009 - 2013 MongoDb Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/server/node_modules/monk/node_modules/mongodb/index.js b/server/node_modules/monk/node_modules/mongodb/index.js deleted file mode 100755 index 4f59e9d9..00000000 --- a/server/node_modules/monk/node_modules/mongodb/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/mongodb'); diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/admin.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/admin.js deleted file mode 100755 index c1f6eb56..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/admin.js +++ /dev/null @@ -1,340 +0,0 @@ -/*! - * Module dependencies. - */ -var Collection = require('./collection').Collection, - Cursor = require('./cursor').Cursor, - DbCommand = require('./commands/db_command').DbCommand, - utils = require('./utils'); - -/** - * Allows the user to access the admin functionality of MongoDB - * - * @class Represents the Admin methods of MongoDB. - * @param {Object} db Current db instance we wish to perform Admin operations on. - * @return {Function} Constructor for Admin type. - */ -function Admin(db) { - if(!(this instanceof Admin)) return new Admin(db); - - /** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from buildInfo or null if an error occured. - * @return {null} Returns no result - * @api public - */ - this.buildInfo = function(callback) { - this.serverInfo(callback); - } - - /** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from serverInfo or null if an error occured. - * @return {null} Returns no result - * @api private - */ - this.serverInfo = function(callback) { - db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { - if(err != null) return callback(err, null); - return callback(null, doc.documents[0]); - }); - } - - /** - * Retrieve this db's server status. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from serverStatus or null if an error occured. - * @return {null} - * @api public - */ - this.serverStatus = function(callback) { - var self = this; - - db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { - if(err == null && doc.documents[0].ok === 1) { - callback(null, doc.documents[0]); - } else { - if(err) return callback(err, false); - return callback(utils.toError(doc.documents[0]), false); - } - }); - }; - - /** - * Retrieve the current profiling Level for MongoDB - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from profilingLevel or null if an error occured. - * @return {null} Returns no result - * @api public - */ - this.profilingLevel = function(callback) { - var self = this; - - db.executeDbAdminCommand({profile:-1}, function(err, doc) { - doc = doc.documents[0]; - - if(err == null && doc.ok === 1) { - var was = doc.was; - if(was == 0) return callback(null, "off"); - if(was == 1) return callback(null, "slow_only"); - if(was == 2) return callback(null, "all"); - return callback(new Error("Error: illegal profiling level value " + was), null); - } else { - err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - } - }); - }; - - /** - * Ping the MongoDB server and retrieve results - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from ping or null if an error occured. - * @return {null} Returns no result - * @api public - */ - this.ping = function(options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - db.executeDbAdminCommand({ping: 1}, args.pop()); - } - - /** - * Authenticate against MongoDB - * - * @param {String} username The user name for the authentication. - * @param {String} password The password for the authentication. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from authenticate or null if an error occured. - * @return {null} Returns no result - * @api public - */ - this.authenticate = function(username, password, callback) { - db.authenticate(username, password, {authdb: 'admin'}, function(err, doc) { - return callback(err, doc); - }) - } - - /** - * Logout current authenticated user - * - * @param {Object} [options] Optional parameters to the command. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from logout or null if an error occured. - * @return {null} Returns no result - * @api public - */ - this.logout = function(callback) { - db.logout({authdb: 'admin'}, function(err, doc) { - return callback(err, doc); - }) - } - - /** - * Add a user to the MongoDB server, if the user exists it will - * overwrite the current password - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - * @param {String} username The user name for the authentication. - * @param {String} password The password for the authentication. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from addUser or null if an error occured. - * @return {null} Returns no result - * @api public - */ - this.addUser = function(username, password, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() : {}; - // Set the db name to admin - options.dbName = 'admin'; - // Add user - db.addUser(username, password, options, function(err, doc) { - return callback(err, doc); - }) - } - /** - * Remove a user from the MongoDB server - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - * @param {String} username The user name for the authentication. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occured. - * @return {null} Returns no result - * @api public - */ - this.removeUser = function(username, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - options.dbName = 'admin'; - - db.removeUser(username, options, function(err, doc) { - return callback(err, doc); - }) - } - - /** - * Set the current profiling level of MongoDB - * - * @param {String} level The new profiling level (off, slow_only, all) - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from setProfilingLevel or null if an error occured. - * @return {null} Returns no result - * @api public - */ - this.setProfilingLevel = function(level, callback) { - var self = this; - var command = {}; - var profile = 0; - - if(level == "off") { - profile = 0; - } else if(level == "slow_only") { - profile = 1; - } else if(level == "all") { - profile = 2; - } else { - return callback(new Error("Error: illegal profiling level value " + level)); - } - - // Set up the profile number - command['profile'] = profile; - - db.executeDbAdminCommand(command, function(err, doc) { - doc = doc.documents[0]; - - if(err == null && doc.ok === 1) - return callback(null, level); - return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - }); - }; - - /** - * Retrive the current profiling information for MongoDB - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from profilingInfo or null if an error occured. - * @return {null} Returns no result - * @api public - */ - this.profilingInfo = function(callback) { - try { - new Cursor(db, new Collection(db, DbCommand.SYSTEM_PROFILE_COLLECTION), {}, {}, {dbName: 'admin'}).toArray(function(err, items) { - return callback(err, items); - }); - } catch (err) { - return callback(err, null); - } - }; - - /** - * Execute a db command against the Admin database - * - * @param {Object} command A command object `{ping:1}`. - * @param {Object} [options] Optional parameters to the command. - * @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter. - * @return {null} Returns no result - * @api public - */ - this.command = function(command, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - - // Execute a command - db.executeDbAdminCommand(command, options, function(err, doc) { - // Ensure change before event loop executes - return callback != null ? callback(err, doc) : null; - }); - } - - /** - * Validate an existing collection - * - * @param {String} collectionName The name of the collection to validate. - * @param {Object} [options] Optional parameters to the command. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from validateCollection or null if an error occured. - * @return {null} Returns no result - * @api public - */ - this.validateCollection = function(collectionName, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - - var self = this; - var command = {validate: collectionName}; - var keys = Object.keys(options); - - // Decorate command with extra options - for(var i = 0; i < keys.length; i++) { - if(options.hasOwnProperty(keys[i])) { - command[keys[i]] = options[keys[i]]; - } - } - - db.command(command, function(err, doc) { - if(err != null) return callback(err, null); - - if(doc.ok === 0) - return callback(new Error("Error with validate command"), null); - if(doc.result != null && doc.result.constructor != String) - return callback(new Error("Error with validation data"), null); - if(doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error("Error: invalid collection " + collectionName), null); - if(doc.valid != null && !doc.valid) - return callback(new Error("Error: invalid collection " + collectionName), null); - - return callback(null, doc); - }); - }; - - /** - * List the available databases - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from listDatabases or null if an error occured. - * @return {null} Returns no result - * @api public - */ - this.listDatabases = function(callback) { - // Execute the listAllDatabases command - db.executeDbAdminCommand({listDatabases:1}, {}, function(err, doc) { - if(err != null) return callback(err, null); - return callback(null, doc.documents[0]); - }); - } - - /** - * Get ReplicaSet status - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from replSetGetStatus or null if an error occured. - * @return {null} - * @api public - */ - this.replSetGetStatus = function(callback) { - var self = this; - - db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { - if(err == null && doc.documents[0].ok === 1) - return callback(null, doc.documents[0]); - if(err) return callback(err, false); - return callback(utils.toError(doc.documents[0]), false); - }); - }; -}; - -/** - * @ignore - */ -exports.Admin = Admin; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/aggregation_cursor.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/aggregation_cursor.js deleted file mode 100755 index 74e0157f..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/aggregation_cursor.js +++ /dev/null @@ -1,191 +0,0 @@ -var ReadPreference = require('./connection/read_preference').ReadPreference - , Readable = require('stream').Readable || require('readable-stream').Readable - , CommandCursor = require('./command_cursor').CommandCursor - , utils = require('./utils') - , shared = require('./collection/shared') - , inherits = require('util').inherits; - -var AggregationCursor = function(collection, serverCapabilities, options) { - var pipe = []; - var self = this; - var results = null; - var _cursor_options = {}; - // Ensure we have options set up - options = options == null ? {} : options; - - // If a pipeline was provided - pipe = Array.isArray(options.pipe) ? options.pipe : pipe; - // Set passed in batchSize if provided - if(typeof options.batchSize == 'number') _cursor_options.batchSize = options.batchSize; - // Get the read Preference - var readPreference = shared._getReadConcern(collection, options); - - // Set up - Readable.call(this, {objectMode: true}); - - // Contains connection - var connection = null; - - // Set the read preference - var _options = { - readPreference: readPreference - }; - - // Actual command - var command = { - aggregate: collection.collectionName - , pipeline: pipe - , cursor: _cursor_options - } - - // If allowDiskUse is set - if(typeof options.allowDiskUse == 'boolean') - command.allowDiskUse = options.allowDiskUse; - - // If maxTimeMS is set - if(typeof options.maxTimeMS == 'number') - command.maxTimeMS = options.maxTimeMS; - - // Command cursor (if we support one) - var commandCursor = new CommandCursor(collection.db, collection, command); - - this.explain = function(callback) { - if(typeof callback != 'function') - throw utils.toError("AggregationCursor explain requires a callback function"); - - // Add explain options - _options.explain = true; - // Execute aggregation pipeline - collection.aggregate(pipe, _options, function(err, results) { - if(err) return callback(err, null); - callback(null, results); - }); - } - - this.get = function(callback) { - if(typeof callback != 'function') - throw utils.toError("AggregationCursor get requires a callback function"); - // Checkout a connection - var _connection = collection.db.serverConfig.checkoutReader(_options.readPreference); - // Fall back - if(!_connection.serverCapabilities.hasAggregationCursor) { - return collection.aggregate(pipe, _options, function(err, results) { - if(err) return callback(err); - callback(null, results); - }); - } - - // Execute get using command Cursor - commandCursor.get({connection: _connection}, callback); - } - - this.getOne = function(callback) { - if(typeof callback != 'function') - throw utils.toError("AggregationCursor getOne requires a callback function"); - // Set the limit to 1 - pipe.push({$limit: 1}); - // For now we have no cursor command so let's just wrap existing results - collection.aggregate(pipe, _options, function(err, results) { - if(err) return callback(err); - callback(null, results[0]); - }); - } - - this.each = function(callback) { - // Checkout a connection if we have none - if(!connection) - connection = collection.db.serverConfig.checkoutReader(_options.readPreference); - - // Fall back - if(!connection.serverCapabilities.hasAggregationCursor) { - return collection.aggregate(pipe, _options, function(err, _results) { - if(err) return callback(err); - - while(_results.length > 0) { - callback(null, _results.shift()); - } - - callback(null, null); - }); - } - - // Execute each using command Cursor - commandCursor.each({connection: connection}, function(err, doc) { - callback(err, doc); - }); - } - - this.next = function(callback) { - if(typeof callback != 'function') - throw utils.toError("AggregationCursor next requires a callback function"); - - // Checkout a connection if we have none - if(!connection) - connection = collection.db.serverConfig.checkoutReader(_options.readPreference); - - // Fall back - if(!connection.serverCapabilities.hasAggregationCursor) { - if(!results) { - // For now we have no cursor command so let's just wrap existing results - return collection.aggregate(pipe, _options, function(err, _results) { - if(err) return callback(err); - results = _results; - - // Ensure we don't issue undefined - var item = results.shift(); - callback(null, item ? item : null); - }); - } - - // Ensure we don't issue undefined - var item = results.shift(); - // Return the item - return callback(null, item ? item : null); - } - - // Execute next using command Cursor - commandCursor.next({connection: connection}, callback); - } - - // - // Close method - // - this.close = function(callback) { - if(typeof callback != 'function') - throw utils.toError("AggregationCursor close requires a callback function"); - - // Checkout a connection if we have none - if(!connection) - connection = collection.db.serverConfig.checkoutReader(_options.readPreference); - - // Fall back - if(!connection.serverCapabilities.hasAggregationCursor) { - return callback(null, null); - } - - // Execute next using command Cursor - commandCursor.close(callback); - } - - // - // Stream method - // - this._read = function(n) { - self.next(function(err, result) { - if(err) { - self.emit('error', err); - return self.push(null); - } - - self.push(result); - }); - } -} - -// Inherit from Readable -if(Readable != null) { - inherits(AggregationCursor, Readable); -} - -// Exports the Aggregation Framework -exports.AggregationCursor = AggregationCursor; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js deleted file mode 100755 index 3484dc36..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js +++ /dev/null @@ -1,81 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , crypto = require('crypto'); - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - var numberOfValidConnections = 0; - var credentialsValid = false; - options = options || {}; - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Return connection option - options.returnConnection = true; - - // Execute nonce command - db.command({'getnonce':1}, options, function(err, result, connection) { - // Execute on all the connections - if(err == null) { - // Nonce used to make authentication request with md5 hash - var nonce = result.nonce; - - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password); - var key = md5.digest('hex'); - - // Creat cmd - var cmd = {'authenticate':1, 'user':username, 'nonce':nonce, 'key':key}; - - // Execute command - db.db(authdb).command(cmd, {connection:connection}, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - - // Ensure we save any error - if(err) { - errorObject = err; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - if(errorObject == null && credentialsValid) { - db.serverConfig.auth.add('MONGODB-CR', db.databaseName, username, password, authdb); - // Return callback - internalCallback(errorObject, true); - } else if(numberOfValidConnections > 0 && numberOfValidConnections != numberOfConnections - && credentialsValid) { - // One or more servers failed on auth (f.ex secondary hanging on foreground indexing) - db.serverConfig.auth.add('MONGODB-CR', db.databaseName, username, password, authdb); - // Return callback - internalCallback(errorObject, true); - } else { - internalCallback(errorObject, false); - } - } - }); - } - }); -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js deleted file mode 100755 index e088d196..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js +++ /dev/null @@ -1,172 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , format = require('util').format; - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; -// Try to grab the Kerberos class -try { - Kerberos = require('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require('kerberos').processes.MongoAuthProcess -} catch(err) {} - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - var numberOfValidConnections = 0; - var credentialsValid = false; - options = options || {}; - - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Grab all the connections - var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections(); - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - - // Start Auth process for a connection - GSSAPIInitialize(db, username, password, authdb, gssapiServiceName, connections[i], function(err, result) { - // Adjust number of connections left to connect - numberOfConnections = numberOfConnections - 1; - - // Ensure we save any error - if(err) { - errorObject = err; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - // We are done - if(errorObject == null && numberOfConnections == 0) { - // We authenticated correctly save the credentials - db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName); - // Return valid callback - return internalCallback(null, true); - } else if(numberOfValidConnections > 0 && numberOfValidConnections != numberOfConnections - && credentialsValid) { - // We authenticated correctly save the credentials - db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName); - // Return valid callback - return internalCallback(null, true); - } else { - return internalCallback(errorObject, false); - } - } - }); - } -} - -// -// Initialize step -var GSSAPIInitialize = function(db, username, password, authdb, gssapiServiceName, connection, callback) { - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.socketOptions.host, connection.socketOptions.port, gssapiServiceName); - - // Perform initialization - mongo_auth_process.init(username, password, function(err, context) { - if(err) return callback(err, false); - - // Perform the first step - mongo_auth_process.transition('', function(err, payload) { - if(err) return callback(err, false); - - // Call the next db step - MongoDBGSSAPIFirstStep(mongo_auth_process, payload, db, username, password, authdb, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPIFirstStep = function(mongo_auth_process, payload, db, username, password, authdb, connection, callback) { - // Build the sasl start command - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: payload - , autoAuthorize: 1 - }; - - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err, false); - // Get the payload - doc = doc.documents[0]; - var db_payload = doc.payload; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err, false); - - // MongoDB API Second Step - MongoDBGSSAPISecondStep(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPISecondStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback) { - // Build Authentication command to send to MongoDB - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err, false); - - // Get the result document - doc = doc.documents[0]; - - // Call next transition for kerberos - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err, false); - - // Call the last and third step - MongoDBGSSAPIThirdStep(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback); - }); - }); -} - -var MongoDBGSSAPIThirdStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback) { - // Build final command - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Let's finish the auth process against mongodb - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err, false); - - mongo_auth_process.transition(null, function(err, payload) { - if(err) return callback(err, false); - callback(null, true); - }); - }); -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js deleted file mode 100755 index d2555cd0..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js +++ /dev/null @@ -1,79 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , crypto = require('crypto') - , Binary = require('bson').Binary - , format = require('util').format; - -var authenticate = function(db, username, password, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - var numberOfValidConnections = 0; - var credentialsValid = false; - options = options || {}; - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Create payload - var payload = new Binary(format("\x00%s\x00%s", username, password)); - - // Let's start the sasl process - var command = { - saslStart: 1 - , mechanism: 'PLAIN' - , payload: payload - , autoAuthorize: 1 - }; - - // Grab all the connections - var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections(); - - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - var connection = connections[i]; - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - - // Ensure we save any error - if(err) { - errorObject = err; - } else if(result.documents[0].err != null || result.documents[0].errmsg != null){ - errorObject = utils.toError(result.documents[0]); - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - if(errorObject == null && credentialsValid) { - // We authenticated correctly save the credentials - db.serverConfig.auth.add('PLAIN', db.databaseName, username, password); - // Return callback - internalCallback(errorObject, true); - } else if(numberOfValidConnections > 0 && numberOfValidConnections != numberOfConnections - && credentialsValid) { - // We authenticated correctly save the credentials - db.serverConfig.auth.add('PLAIN', db.databaseName, username, password); - // Return callback - internalCallback(errorObject, true); - } else { - internalCallback(errorObject, false); - } - } - }); - } -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js deleted file mode 100755 index 32ed15f7..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js +++ /dev/null @@ -1,251 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , crypto = require('crypto') - , Binary = require('bson').Binary - , f = require('util').format; - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - var numberOfValidConnections = 0; - var credentialsValid = false; - options = options || {}; - - // Grab all the connections - var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections().slice(0); - if(connections.length > 1) { - options['onAll'] = true; - } - - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var executeScram = function(connection) { - // Clean up the user - username = username.replace('=', "=3D").replace(',', '=2C'); - - // Create a random nonce - var nonce = crypto.randomBytes(24).toString('base64'); - // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc' - var firstBare = f("n=%s,r=%s", username, nonce); - - // Build command structure - var cmd = { - saslStart: 1 - , mechanism: 'SCRAM-SHA-1' - , payload: new Binary(f("n,,%s", firstBare)) - , autoAuthorize: 1 - } - - // Handle the error - var handleError = function(err, r) { - if(err) { - errorObject = err; return false; - } else if(r['$err']) { - errorObject = r; return false; - } else if(r['errmsg']) { - errorObject = r; return false; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - return true - } - - // Finish up - var finish = function(_count, _numberOfValidConnections) { - if(_count == 0 && _numberOfValidConnections > 0) { - db.serverConfig.auth.add('SCRAM-SHA-1', db.databaseName, username, password, authdb); - // Return correct authentication - return callback(null, true); - } else if(_count == 0) { - if(errorObject == null) errorObject = utils.toError(f("failed to authenticate using scram")); - return callback(errorObject, false); - } - } - - var handleEnd = function(_err, _r) { - // Handle any error - handleError(_err, _r) - // Adjust the number of connections - count = count - 1; - // Execute the finish - finish(count, numberOfValidConnections); - } - - // Execute start sasl command - db.db(authdb).command(cmd, { connection: connection }, function(err, r) { - // Do we have an error, handle it - if(handleError(err, r) == false) { - count = count - 1; - - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(new AuthSession(db, username, password)); - // Return correct authentication - return callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = utils.toError(f("failed to authenticate using scram")); - return callback(errorObject, false); - } - - return; - } - - // Get the dictionary - var dict = parsePayload(r.payload.value()) - - // Unpack dictionary - var iterations = parseInt(dict.i, 10); - var salt = dict.s; - var rnonce = dict.r; - - // Set up start of proof - var withoutProof = f("c=biws,r=%s", rnonce); - var passwordDig = passwordDigest(username, password); - var saltedPassword = hi(passwordDig - , new Buffer(salt, 'base64') - , iterations); - - // Create the client key - var hmac = crypto.createHmac('sha1', saltedPassword); - hmac.update(new Buffer("Client Key")); - var clientKey = hmac.digest(); - - // Create the stored key - var hash = crypto.createHash('sha1'); - hash.update(clientKey); - var storedKey = hash.digest(); - - // Create the authentication message - var authMsg = [firstBare, r.payload.value().toString('base64'), withoutProof].join(','); - - // Create client signature - var hmac = crypto.createHmac('sha1', storedKey); - hmac.update(new Buffer(authMsg)); - var clientSig = hmac.digest(); - - // Create client proof - var clientProof = f("p=%s", new Buffer(xor(clientKey, clientSig)).toString('base64')); - - // Create client final - var clientFinal = [withoutProof, clientProof].join(','); - - // Generate server key - var hmac = crypto.createHmac('sha1', saltedPassword); - hmac.update(new Buffer('Server Key')) - var serverKey = hmac.digest(); - - // Generate server signature - var hmac = crypto.createHmac('sha1', serverKey); - hmac.update(new Buffer(authMsg)) - var serverSig = hmac.digest(); - - // - // Create continue message - var cmd = { - saslContinue: 1 - , conversationId: r.conversationId - , payload: new Binary(new Buffer(clientFinal)) - } - - // - // Execute sasl continue - db.db(authdb).command(cmd, { connection: connection }, function(err, r) { - if(err) return handleEnd(err, r); - if(r && r.done == false) { - var cmd = { - saslContinue: 1 - , conversationId: r.conversationId - , payload: new Buffer(0) - } - - db.db(authdb).command(cmd, { connection: connection }, function(err, r) { - handleEnd(err, r); - }); - } else { - handleEnd(err, r); - } - }); - }); - } - - // Get the connection - executeScram(connections.shift()); - } -} - -var parsePayload = function(payload) { - var dict = {}; - var parts = payload.split(','); - - for(var i = 0; i < parts.length; i++) { - var valueParts = parts[i].split('='); - dict[valueParts[0]] = valueParts[1]; - } - - return dict; -} - -var passwordDigest = function(username, password) { - if(typeof username != 'string') throw utils.toError("username must be a string"); - if(typeof password != 'string') throw utils.toError("password must be a string"); - if(password.length == 0) throw utils.toError("password cannot be empty"); - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - return md5.digest('hex'); -} - -// XOR two buffers -var xor = function(a, b) { - if (!Buffer.isBuffer(a)) a = new Buffer(a) - if (!Buffer.isBuffer(b)) b = new Buffer(b) - var res = [] - if (a.length > b.length) { - for (var i = 0; i < b.length; i++) { - res.push(a[i] ^ b[i]) - } - } else { - for (var i = 0; i < a.length; i++) { - res.push(a[i] ^ b[i]) - } - } - return new Buffer(res); -} - -// Create a final digest -var hi = function(data, salt, iterations) { - // Create digest - var digest = function(msg) { - var hmac = crypto.createHmac('sha1', data); - hmac.update(msg); - var result = hmac.digest() - return result; - } - - // Create variables - salt = Buffer.concat([salt, new Buffer('\x00\x00\x00\x01')]) - var ui = digest(salt); - var u1 = ui; - - for(var i = 0; i < iterations - 1; i++) { - u1 = digest(u1); - ui = xor(ui, u1); - } - - return ui; -} - -exports.authenticate = authenticate; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js deleted file mode 100755 index 13a87ea5..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js +++ /dev/null @@ -1,156 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , format = require('util').format; - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; -// Try to grab the Kerberos class -try { - Kerberos = require('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require('kerberos').processes.MongoAuthProcess -} catch(err) {} - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - var numberOfValidConnections = 0; - var credentialsValid = false; - options = options || {}; - - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Set the sspi server name - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - - // Grab all the connections - var connections = db.serverConfig.allRawConnections(); - - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - // Start Auth process for a connection - SSIPAuthenticate(db, username, password, authdb, gssapiServiceName, connections[i], function(err, result) { - // Adjust number of connections left to connect - numberOfConnections = numberOfConnections - 1; - - // Ensure we save any error - if(err) { - errorObject = err; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - if(errorObject == null) { - // We authenticated correctly save the credentials - db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName); - // Return valid callback - return internalCallback(null, true); - } else if(numberOfValidConnections > 0 && numberOfValidConnections != numberOfConnections - && credentialsValid) { - // We authenticated correctly save the credentials - db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName); - // Return valid callback - return internalCallback(null, true); - } else { - return internalCallback(errorObject, false); - } - } - }); - } -} - -var SSIPAuthenticate = function(db, username, password, authdb, service_name, connection, callback) { - // -------------------------------------------------------------- - // Async Version - // -------------------------------------------------------------- - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: '' - , autoAuthorize: 1 - }; - - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.socketOptions.host, connection.socketOptions.port, service_name); - - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - mongo_auth_process.init(username, password, function(err) { - if(err) return callback(err); - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - if(doc.done) return callback(null, true); - callback(new Error("Authentication failed"), false); - }); - }); - }); - }); - }); - }); - }); - }); -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js deleted file mode 100755 index 8b8b7c23..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js +++ /dev/null @@ -1,68 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , Binary = require('bson').Binary - , format = require('util').format; - -var authenticate = function(db, username, password, options, callback, t) { - var numberOfConnections = 0; - var errorObject = null; - var numberOfValidConnections = 0; - var credentialsValid = false; - options = options || {}; - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Let's start the sasl process - var command = { - authenticate: 1 - , mechanism: 'MONGODB-X509' - , user: username - }; - - // Grab all the connections - var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections(); - - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - var connection = connections[i]; - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - - // Ensure we save any error - if(err) { - errorObject = err; - } else if(result.documents[0].err != null || result.documents[0].errmsg != null){ - errorObject = utils.toError(result.documents[0]); - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - if(errorObject == null && credentialsValid) { - // We authenticated correctly save the credentials - db.serverConfig.auth.add('MONGODB-X509', db.databaseName, username, password); - // Return callback - internalCallback(errorObject, true); - } else { - internalCallback(errorObject, false); - } - } - }); - } -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection.js deleted file mode 100755 index 3d641f67..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection.js +++ /dev/null @@ -1,688 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -var InsertCommand = require('./commands/insert_command').InsertCommand - , QueryCommand = require('./commands/query_command').QueryCommand - , DeleteCommand = require('./commands/delete_command').DeleteCommand - , UpdateCommand = require('./commands/update_command').UpdateCommand - , DbCommand = require('./commands/db_command').DbCommand - , ObjectID = require('bson').ObjectID - , Code = require('bson').Code - , Cursor = require('./cursor').Cursor - , utils = require('./utils') - , shared = require('./collection/shared') - , core = require('./collection/core') - , query = require('./collection/query') - , index = require('./collection/index') - , geo = require('./collection/geo') - , commands = require('./collection/commands') - , aggregation = require('./collection/aggregation') - , unordered = require('./collection/batch/unordered') - , ordered = require('./collection/batch/ordered'); - -/** - * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) - * - * Options - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **slaveOk** {Boolean, default:false}, Allow reads from secondaries. - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **raw** {Boolean, default:false}, perform all operations using raw bson objects. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - * @class Represents a Collection - * @param {Object} db db instance. - * @param {String} collectionName collection name. - * @param {Object} [pkFactory] alternative primary key factory. - * @param {Object} [options] additional options for the collection. - * @return {Object} a collection instance. - */ -function Collection (db, collectionName, pkFactory, options) { - if(!(this instanceof Collection)) return new Collection(db, collectionName, pkFactory, options); - - shared.checkCollectionName(collectionName); - - this.db = db; - this.collectionName = collectionName; - this.internalHint = null; - this.opts = options != null && ('object' === typeof options) ? options : {}; - this.slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - this.serializeFunctions = options == null || options.serializeFunctions == null ? db.serializeFunctions : options.serializeFunctions; - this.raw = options == null || options.raw == null ? db.raw : options.raw; - - // Assign the right collection level readPreference - if(options && options.readPreference) { - this.readPreference = options.readPreference; - } else if(this.db.options.readPreference) { - this.readPreference = this.db.options.readPreference; - } else if(this.db.serverConfig.options.readPreference) { - this.readPreference = this.db.serverConfig.options.readPreference; - } - - // Set custom primary key factory if provided - this.pkFactory = pkFactory == null - ? ObjectID - : pkFactory; - - // Server Capabilities - this.serverCapabilities = this.db.serverConfig._serverCapabilities; -} - -/** - * Inserts a single document or a an array of documents into MongoDB. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **continueOnError/keepGoing** {Boolean, default:false}, keep inserting documents even if one document has an error, *mongodb 1.9.1 >*. - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **forceServerObjectId** {Boolean, default:false}, let server assign ObjectId instead of the driver - * - **checkKeys** {Boolean, default:true}, allows for disabling of document key checking (WARNING OPENS YOU UP TO INJECTION ATTACKS) - * - **fullResult** {Boolean, default:false}, returns the full result document (document returned will differ by server version) - * - * @param {Array|Object} docs - * @param {Object} [options] optional options for insert command - * @param {Function} [callback] optional callback for the function, must be provided when using a writeconcern - * @return {Collection} - * @api public - */ -Collection.prototype.insert = function() { return core.insert; }(); - -/** - * Removes documents specified by `selector` from the db. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **single** {Boolean, default:false}, removes the first document found. - * - **fullResult** {Boolean, default:false}, returns the full result document (document returned will differ by server version) - * - * @param {Object} [selector] optional select, no selector is equivalent to removing all documents. - * @param {Object} [options] additional options during remove. - * @param {Function} [callback] must be provided if you performing a remove with a writeconcern - * @return {null} - * @api public - */ -Collection.prototype.remove = function() { return core.remove; }(); - -/** - * Renames the collection. - * - * Options - * - **dropTarget** {Boolean, default:false}, drop the target name collection if it previously exists. - * - * @param {String} newName the new name of the collection. - * @param {Object} [options] returns option results. - * @param {Function} callback the callback accepting the result - * @return {null} - * @api public - */ -Collection.prototype.rename = function() { return commands.rename; }(); - -/** - * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic - * operators and update instead for more efficient operations. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - * @param {Object} [doc] the document to save - * @param {Object} [options] additional options during remove. - * @param {Function} [callback] must be provided if you performing an update with a writeconcern - * @return {null} - * @api public - */ -Collection.prototype.save = function() { return core.save; }(); - -/** - * Updates documents. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **upsert** {Boolean, default:false}, perform an upsert operation. - * - **multi** {Boolean, default:false}, update all documents matching the selector. - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **checkKeys** {Boolean, default:true}, allows for disabling of document key checking (WARNING OPENS YOU UP TO INJECTION ATTACKS) - * - **fullResult** {Boolean, default:false}, returns the full result document (document returned will differ by server version) - * - * @param {Object} selector the query to select the document/documents to be updated - * @param {Object} document the fields/vals to be updated, or in the case of an upsert operation, inserted. - * @param {Object} [options] additional options during update. - * @param {Function} [callback] must be provided if you performing an update with a writeconcern - * @return {null} - * @api public - */ -Collection.prototype.update = function() { return core.update; }(); - -/** - * The distinct command returns returns a list of distinct values for the given key across a collection. - * - * Options - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {String} key key to run distinct against. - * @param {Object} [query] option query to narrow the returned objects. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from distinct or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.distinct = function() { return commands.distinct; }(); - -/** - * Count number of matching documents in the db to a query. - * - * Options - * - **skip** {Number}, The number of documents to skip for the count. - * - **limit** {Number}, The limit of documents to count. - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Object} [query] query to filter by before performing count. - * @param {Object} [options] additional options during count. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the count method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.count = function() { return commands.count; }(); - -/** - * Drop the collection - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the drop method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.drop = function drop(callback) { - this.db.dropCollection(this.collectionName, callback); -}; - -/** - * Find and update a document. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **remove** {Boolean, default:false}, set to true to remove the object before returning. - * - **upsert** {Boolean, default:false}, perform an upsert operation. - * - **new** {Boolean, default:false}, set to true if you want to return the modified object rather than the original. Ignored for remove. - * - * @param {Object} query query object to locate the object to modify - * @param {Array} sort - if multiple docs match, choose the first one in the specified sort order as the object to manipulate - * @param {Object} doc - the fields/vals to be updated - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findAndModify method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.findAndModify = function() { return core.findAndModify; }(); - -/** - * Find and remove a document - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - * @param {Object} query query object to locate the object to modify - * @param {Array} sort - if multiple docs match, choose the first one in the specified sort order as the object to manipulate - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findAndRemove method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.findAndRemove = function() { return core.findAndRemove; }(); - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * - * Various argument possibilities - * - callback? - * - selector, callback?, - * - selector, fields, callback? - * - selector, options, callback? - * - selector, fields, options, callback? - * - selector, fields, skip, limit, callback? - * - selector, fields, skip, limit, timeout, callback? - * - * Options - * - **limit** {Number, default:0}, sets the limit of documents returned in the query. - * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * - **fields** {Object}, the fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * - **skip** {Number, default:0}, set to skip N documents ahead in your query (useful for pagination). - * - **hint** {Object}, tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * - **explain** {Boolean, default:false}, explain the query instead of returning the data. - * - **snapshot** {Boolean, default:false}, snapshot query. - * - **timeout** {Boolean, default:true}, specify if the cursor can timeout. - * - **tailable** {Boolean, default:false}, specify if the cursor is tailable. - * - **tailableRetryInterval** {Number, default:100}, specify the miliseconds between getMores on tailable cursor. - * - **numberOfRetries** {Number, default:5}, specify the number of times to retry the tailable cursor. - * - **awaitdata** {Boolean, default:false} allow the cursor to wait for data, only applicable for tailable cursor. - * - **oplogReplay** {Boolean, default:false} sets an internal flag, only applicable for tailable cursor. - * - **exhaust** {Boolean, default:false} have the server send all the documents at once as getMore packets, not recommended. - * - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results. - * - **returnKey** {Boolean, default:false}, only return the index key. - * - **maxScan** {Number}, Limit the number of items to scan. - * - **min** {Number}, Set index bounds. - * - **max** {Number}, Set index bounds. - * - **showDiskLoc** {Boolean, default:false}, Show disk location of results. - * - **comment** {String}, You can put a $comment field on a query to make looking in the profiler logs simpler. - * - **raw** {Boolean, default:false}, Return all BSON documents as Raw Buffer documents. - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **numberOfRetries** {Number, default:5}, if using awaidata specifies the number of times to retry on timeout. - * - **partial** {Boolean, default:false}, specify if the cursor should return partial results when querying against a sharded system - * - **maxTimeMS** {Number}, number of miliseconds to wait before aborting the query. - * - * @param {Object|ObjectID} query query object to locate the object to modify - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the find method or null if an error occured. - * @return {Cursor} returns a cursor to the query - * @api public - */ -Collection.prototype.find = function() { return query.find; }(); - -/** - * Finds a single document based on the query - * - * Various argument possibilities - * - callback? - * - selector, callback?, - * - selector, fields, callback? - * - selector, options, callback? - * - selector, fields, options, callback? - * - selector, fields, skip, limit, callback? - * - selector, fields, skip, limit, timeout, callback? - * - * Options - * - **limit** {Number, default:0}, sets the limit of documents returned in the query. - * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * - **fields** {Object}, the fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * - **skip** {Number, default:0}, set to skip N documents ahead in your query (useful for pagination). - * - **hint** {Object}, tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * - **explain** {Boolean, default:false}, explain the query instead of returning the data. - * - **snapshot** {Boolean, default:false}, snapshot query. - * - **timeout** {Boolean, default:false}, specify if the cursor can timeout. - * - **tailable** {Boolean, default:false}, specify if the cursor is tailable. - * - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results. - * - **returnKey** {Boolean, default:false}, only return the index key. - * - **maxScan** {Number}, Limit the number of items to scan. - * - **min** {Number}, Set index bounds. - * - **max** {Number}, Set index bounds. - * - **showDiskLoc** {Boolean, default:false}, Show disk location of results. - * - **comment** {String}, You can put a $comment field on a query to make looking in the profiler logs simpler. - * - **raw** {Boolean, default:false}, Return all BSON documents as Raw Buffer documents. - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **partial** {Boolean, default:false}, specify if the cursor should return partial results when querying against a sharded system - * - **maxTimeMS** {Number}, number of miliseconds to wait before aborting the query. - * - * @param {Object|ObjectID} query query object to locate the object to modify - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findOne method or null if an error occured. - * @return {Cursor} returns a cursor to the query - * @api public - */ -Collection.prototype.findOne = function() { return query.findOne; }(); - -/** - * Creates an index on the collection. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the createIndex method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.createIndex = function() { return index.createIndex; }(); - -/** - * Ensures that an index exists, if it does not it creates it - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the ensureIndex method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.ensureIndex = function() { return index.ensureIndex; }(); - -/** - * Get the list of all indexes information for the collection. - * - * Options - * - **batchSize**, {Number, 0} The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * - * @param {Object} [options] additional options during update. - * @return {Cursor} - */ -Collection.prototype.listIndexes = function() { return index.listIndexes; }(); - -/** - * Retrieves this collections index info. - * - * Options - * - **full** {Boolean, default:false}, returns the full raw index information. - * - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexInformation method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.indexInformation = function() { return index.indexInformation; }(); - -/** - * Drops an index from this collection. - * - * @param {String} name - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropIndex method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.dropIndex = function dropIndex (name, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - // Execute dropIndex command - this.db.dropIndex(this.collectionName, name, options, callback); -}; - -/** - * Drops all indexes from this collection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropAllIndexes method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.dropAllIndexes = function() { return index.dropAllIndexes; }(); - -/** - * Drops all indexes from this collection. - * - * @deprecated - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropIndexes method or null if an error occured. - * @return {null} - * @api private - */ -Collection.prototype.dropIndexes = function() { return Collection.prototype.dropAllIndexes; }(); - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the reIndex method or null if an error occured. - * @return {null} - * @api public -**/ -Collection.prototype.reIndex = function(options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - // Execute reIndex - this.db.reIndex(this.collectionName, options, callback); -} - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * Options - * - **out** {Object}, sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * - **query** {Object}, query filter object. - * - **sort** {Object}, sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * - **limit** {Number}, number of objects to return from collection. - * - **keeptemp** {Boolean, default:false}, keep temporary data. - * - **finalize** {Function | String}, finalize function. - * - **scope** {Object}, can pass in variables that can be access from map/reduce/finalize. - * - **jsMode** {Boolean, default:false}, it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. - * - **verbose** {Boolean, default:false}, provide statistics on job execution time. - * - **readPreference** {String, only for inline results}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Function|String} map the mapping function. - * @param {Function|String} reduce the reduce function. - * @param {Objects} [options] options for the map reduce job. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the mapReduce method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.mapReduce = function() { return aggregation.mapReduce; }(); - -/** - * Run a group command across a collection - * - * Options - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Object|Array|Function|Code} keys an object, array or function expressing the keys to group by. - * @param {Object} condition an optional condition that must be true for a row to be considered. - * @param {Object} initial initial value of the aggregation counter object. - * @param {Function|Code} reduce the reduce function aggregates (reduces) the objects iterated - * @param {Function|Code} finalize an optional function to be run on each item in the result set just before the item is returned. - * @param {Boolean} command specify if you wish to run using the internal group command or using eval, default is true. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the group method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.group = function() { return aggregation.group; }(); - -/** - * Returns the options of the collection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the options method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.options = function() { return commands.options; }(); - -/** - * Returns if the collection is a capped collection - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the isCapped method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.isCapped = function() { return commands.isCapped; }(); - -/** - * Checks if one or more indexes exist on the collection - * - * @param {String|Array} indexNames check if one or more indexes exist on the collection. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexExists method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.indexExists = function() { return index.indexExists; }(); - -/** - * Execute the geoNear command to search for items in the collection - * - * Options - * - **num** {Number}, max number of results to return. - * - **minDistance** {Number}, include results starting at minDistance from a point (2.6 or higher) - * - **maxDistance** {Number}, include results up to maxDistance from the point. - * - **distanceMultiplier** {Number}, include a value to multiply the distances with allowing for range conversions. - * - **query** {Object}, filter the results by a query. - * - **spherical** {Boolean, default:false}, perform query using a spherical model. - * - **uniqueDocs** {Boolean, default:false}, the closest location in a document to the center of the search region will always be returned MongoDB > 2.X. - * - **includeLocs** {Boolean, default:false}, include the location data fields in the top level of the results MongoDB > 2.X. - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Number} x point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {Number} y point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {Objects} [options] options for the map reduce job. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoNear method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.geoNear = function() { return geo.geoNear; }(); - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * Options - * - **maxDistance** {Number}, include results up to maxDistance from the point. - * - **search** {Object}, filter the results by a query. - * - **limit** {Number}, max number of results to return. - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Number} x point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {Number} y point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {Objects} [options] options for the map reduce job. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoHaystackSearch method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.geoHaystackSearch = function() { return geo.geoHaystackSearch; }(); - -/** - * Retrieve all the indexes on the collection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexes method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.indexes = function indexes(callback) { - this.db.indexInformation(this.collectionName, {full:true}, callback); -} - -/** - * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 - * - * Options - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **cursor** {Object}, return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * - **cursor.batchSize** {Number}, the batchSize for the cursor - * - **out** {String}, the collection name to where to write the results from the aggregation (MongoDB 2.6 or higher). Warning any existing collection will be overwritten. - * - **explain** {Boolean, default:false}, explain returns the aggregation execution plan (requires mongodb 2.6 >). - * - **allowDiskUse** {Boolean, default:false}, allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * - **maxTimeMS** {Number}, maxTimeMS the maxTimeMS operator specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * - * @param {Array} array containing all the aggregation framework commands for the execution. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the aggregate method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.aggregate = function() { return aggregation.aggregate; }(); - -/** - * Get all the collection statistics. - * - * Options - * - **scale** {Number}, divide the returned sizes by scale value. - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Objects} [options] options for the stats command. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the stats method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.stats = function() { return commands.stats; }(); - -/** - * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - * @param {Objects} [options] options for the initializeUnorderedBatch - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. The second argument will be a UnorderedBulkOperation object. - * @return {UnorderedBulkOperation} - * @api public - */ -Collection.prototype.initializeUnorderedBulkOp = function() { return unordered.initializeUnorderedBulkOp; }(); - -/** - * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - * @param {Objects} [options] options for the initializeOrderedBulkOp - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. The second argument will be a OrderedBulkOperation object. - * @return {OrderedBulkOperation} - * @api public - */ -Collection.prototype.initializeOrderedBulkOp = function() { return ordered.initializeOrderedBulkOp; }(); - -/** - * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are - * no ordering guarantees for returned results. - * - * Options - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results. - * - **numCursors**, {Number, 1} the maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) - * - * @param {Objects} [options] options for the initializeOrderedBulkOp - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. The second argument will be an array of CommandCursor instances. - * @return {OrderedBulkOperation} - * @api public - */ -Collection.prototype.parallelCollectionScan = function() { return query.parallelCollectionScan; }(); - -/** - * @ignore - */ -Object.defineProperty(Collection.prototype, "hint", { - enumerable: true - , get: function () { - return this.internalHint; - } - , set: function (v) { - this.internalHint = shared.normalizeHintField(v); - } -}); - -/** - * Expose. - */ -exports.Collection = Collection; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/aggregation.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/aggregation.js deleted file mode 100755 index 64a4ad5f..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/aggregation.js +++ /dev/null @@ -1,325 +0,0 @@ -var shared = require('./shared') - , utils = require('../utils') - , AggregationCursor = require('../aggregation_cursor').AggregationCursor - , Code = require('bson').Code - , DbCommand = require('../commands/db_command').DbCommand; - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope (scope) { - if (!utils.isObject(scope)) { - return scope; - } - - var keys = Object.keys(scope); - var i = keys.length; - var key; - var new_scope = {}; - - while (i--) { - key = keys[i]; - if ('function' == typeof scope[key]) { - new_scope[key] = new Code(String(scope[key])); - } else { - new_scope[key] = processScope(scope[key]); - } - } - - return new_scope; -} - -var pipe = function() { - return new AggregationCursor(this, this.serverCapabilities); -} - -var mapReduce = function mapReduce (map, reduce, options, callback) { - if ('function' === typeof options) callback = options, options = {}; - // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) - if(null == options.out) { - throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); - } - - if ('function' === typeof map) { - map = map.toString(); - } - - if ('function' === typeof reduce) { - reduce = reduce.toString(); - } - - if ('function' === typeof options.finalize) { - options.finalize = options.finalize.toString(); - } - - var mapCommandHash = { - mapreduce: this.collectionName - , map: map - , reduce: reduce - }; - - // Add any other options passed in - for (var name in options) { - if ('scope' == name) { - mapCommandHash[name] = processScope(options[name]); - } else { - mapCommandHash[name] = options[name]; - } - } - - // Set read preference if we set one - var readPreference = shared._getReadConcern(this, options); - - // If we have a read preference and inline is not set as output fail hard - if((readPreference != false && readPreference != 'primary') - && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { - readPreference = 'primary'; - } - - // self - var self = this; - var cmd = DbCommand.createDbCommand(this.db, mapCommandHash); - - this.db._executeQueryCommand(cmd, {readPreference:readPreference}, function (err, result) { - if(err) return callback(err); - if(!result || !result.documents || result.documents.length == 0) - return callback(Error("command failed to return results"), null) - - // Check if we have an error - if(1 != result.documents[0].ok || result.documents[0].err || result.documents[0].errmsg) { - return callback(utils.toError(result.documents[0])); - } - - // Create statistics value - var stats = {}; - if(result.documents[0].timeMillis) stats['processtime'] = result.documents[0].timeMillis; - if(result.documents[0].counts) stats['counts'] = result.documents[0].counts; - if(result.documents[0].timing) stats['timing'] = result.documents[0].timing; - - // invoked with inline? - if(result.documents[0].results) { - // If we wish for no verbosity - if(options['verbose'] == null || !options['verbose']) { - return callback(null, result.documents[0].results); - } - return callback(null, result.documents[0].results, stats); - } - - // The returned collection - var collection = null; - - // If we have an object it's a different db - if(result.documents[0].result != null && typeof result.documents[0].result == 'object') { - var doc = result.documents[0].result; - collection = self.db.db(doc.db).collection(doc.collection); - } else { - // Create a collection object that wraps the result collection - collection = self.db.collection(result.documents[0].result) - } - - // If we wish for no verbosity - if(options['verbose'] == null || !options['verbose']) { - return callback(err, collection); - } - - // Return stats as third set of values - callback(err, collection, stats); - }); -}; - -/** - * Group function helper - * @ignore - */ -var groupFunction = function () { - var c = db[ns].find(condition); - var map = new Map(); - var reduce_function = reduce; - - while (c.hasNext()) { - var obj = c.next(); - var key = {}; - - for (var i = 0, len = keys.length; i < len; ++i) { - var k = keys[i]; - key[k] = obj[k]; - } - - var aggObj = map.get(key); - - if (aggObj == null) { - var newObj = Object.extend({}, key); - aggObj = Object.extend(newObj, initial); - map.put(key, aggObj); - } - - reduce_function(obj, aggObj); - } - - return { "result": map.values() }; -}.toString(); - -var group = function group(keys, condition, initial, reduce, finalize, command, options, callback) { - var args = Array.prototype.slice.call(arguments, 3); - callback = args.pop(); - // Fetch all commands - reduce = args.length ? args.shift() : null; - finalize = args.length ? args.shift() : null; - command = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Make sure we are backward compatible - if(!(typeof finalize == 'function')) { - command = finalize; - finalize = null; - } - - if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys instanceof Code)) { - keys = Object.keys(keys); - } - - if(typeof reduce === 'function') { - reduce = reduce.toString(); - } - - if(typeof finalize === 'function') { - finalize = finalize.toString(); - } - - // Set up the command as default - command = command == null ? true : command; - - // Execute using the command - if(command) { - var reduceFunction = reduce instanceof Code - ? reduce - : new Code(reduce); - - var selector = { - group: { - 'ns': this.collectionName - , '$reduce': reduceFunction - , 'cond': condition - , 'initial': initial - , 'out': "inline" - } - }; - - // if finalize is defined - if(finalize != null) selector.group['finalize'] = finalize; - // Set up group selector - if ('function' === typeof keys || keys instanceof Code) { - selector.group.$keyf = keys instanceof Code - ? keys - : new Code(keys); - } else { - var hash = {}; - keys.forEach(function (key) { - hash[key] = 1; - }); - selector.group.key = hash; - } - - // Set read preference if we set one - var readPreference = shared._getReadConcern(this, options); - // Execute command - this.db.command(selector, {readPreference: readPreference}, function(err, result) { - if(err) return callback(err, null); - callback(null, result.retval); - }); - } else { - // Create execution scope - var scope = reduce != null && reduce instanceof Code - ? reduce.scope - : {}; - - scope.ns = this.collectionName; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - this.db.eval(new Code(groupfn, scope), function (err, results) { - if (err) return callback(err, null); - callback(null, results.result || results); - }); - } -}; - -var aggregate = function(pipeline, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - var self = this; - - // If we have any of the supported options in the options object - var opts = args[args.length - 1] || {}; - options = opts.readPreference - || opts.explain - || opts.cursor - || opts.out - || opts.maxTimeMS - || opts.allowDiskUse ? args.pop() : {} - - // If the callback is the option (as for cursor override it) - if(typeof callback == 'object' && callback != null) options = callback; - - // Convert operations to an array - if(!Array.isArray(args[0])) { - pipeline = []; - // Push all the operations to the pipeline - for(var i = 0; i < args.length; i++) pipeline.push(args[i]); - } - - // Is the user requesting a cursor - if(options.cursor != null && options.out == null) { - if(typeof options.cursor != 'object') throw utils.toError('cursor options must be an object'); - // Set the aggregation cursor options - var agg_cursor_options = options.cursor; - agg_cursor_options.pipe = pipeline; - agg_cursor_options.allowDiskUse = options.allowDiskUse == null ? false : options.allowDiskUse; - // Set the maxTimeMS if passed in - if(typeof options.maxTimeMS == 'number') agg_cursor_options.maxTimeMS = options.maxTimeMS; - // Return the aggregation cursor - return new AggregationCursor(this, this.serverCapabilities, agg_cursor_options); - } - - // If out was specified - if(typeof options.out == 'string') { - pipeline.push({$out: options.out}); - } - - // Build the command - var command = { aggregate : this.collectionName, pipeline : pipeline}; - // If we have allowDiskUse defined - if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; - // Set the maxTimeMS if passed in - if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; - - // Ensure we have the right read preference inheritance - options.readPreference = shared._getReadConcern(this, options); - // If explain has been specified add it - if(options.explain) command.explain = options.explain; - // Execute the command - this.db.command(command, options, function(err, result) { - if(err) { - callback(err); - } else if(result['err'] || result['errmsg']) { - callback(utils.toError(result)); - } else if(typeof result == 'object' && result['serverPipeline']) { - callback(null, result['serverPipeline']); - } else if(typeof result == 'object' && result['stages']) { - callback(null, result['stages']); - } else { - callback(null, result.result); - } - }); -} - -exports.mapReduce = mapReduce; -exports.group = group; -exports.aggregate = aggregate; -exports.pipe = pipe; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/batch/common.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/batch/common.js deleted file mode 100755 index 3a6cb4b1..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/batch/common.js +++ /dev/null @@ -1,440 +0,0 @@ -var utils = require('../../utils'); - -// Error codes -var UNKNOWN_ERROR = 8; -var INVALID_BSON_ERROR = 22; -var WRITE_CONCERN_ERROR = 64; -var MULTIPLE_ERROR = 65; - -// Insert types -var INSERT = 1; -var UPDATE = 2; -var REMOVE = 3 - -/** - * Helper function to define properties - */ -var defineReadOnlyProperty = function(self, name, value) { - Object.defineProperty(self, name, { - enumerable: true - , get: function() { - return value; - } - }); -} - -/** - * Keeps the state of a unordered batch so we can rewrite the results - * correctly after command execution - */ -var Batch = function(batchType, originalZeroIndex) { - this.originalZeroIndex = originalZeroIndex; - this.currentIndex = 0; - this.originalIndexes = []; - this.batchType = batchType; - this.operations = []; - this.size = 0; - this.sizeBytes = 0; -} - -/** - * Wraps a legacy operation so we can correctly rewrite it's error - */ -var LegacyOp = function(batchType, operation, index) { - this.batchType = batchType; - this.index = index; - this.operation = operation; -} - -/** - * Create a new BatchWriteResult instance (INTERNAL TYPE, do not instantiate directly) - * - * @class Represents a BatchWriteResult - * @property **ok** {boolean} did bulk operation correctly execute - * @property **nInserted** {number} number of inserted documents - * @property **nUpdated** {number} number of documents updated logically - * @property **nUpserted** {number} number of upserted documents - * @property **nModified** {number} number of documents updated physically on disk - * @property **nRemoved** {number} number of removed documents - * @param {Object} batchResult internal data structure with results. - * @return {BatchWriteResult} a BatchWriteResult instance - */ -var BatchWriteResult = function(bulkResult) { - defineReadOnlyProperty(this, "ok", bulkResult.ok); - defineReadOnlyProperty(this, "nInserted", bulkResult.nInserted); - defineReadOnlyProperty(this, "nUpserted", bulkResult.nUpserted); - defineReadOnlyProperty(this, "nMatched", bulkResult.nMatched); - defineReadOnlyProperty(this, "nModified", bulkResult.nModified); - defineReadOnlyProperty(this, "nRemoved", bulkResult.nRemoved); - - /** - * Return an array of upserted ids - * - * @return {Array} - * @api public - */ - this.getUpsertedIds = function() { - return bulkResult.upserted; - } - - /** - * Return the upserted id at position x - * - * @param {Number} index the number of the upserted id to return, returns undefined if no result for passed in index - * @return {Array} - * @api public - */ - this.getUpsertedIdAt = function(index) { - return bulkResult.upserted[index]; - } - - /** - * Return raw internal result - * - * @return {Object} - * @api public - */ - this.getRawResponse = function() { - return bulkResult; - } - - /** - * Returns true if the bulk operation contains a write error - * - * @return {Boolean} - * @api public - */ - this.hasWriteErrors = function() { - return bulkResult.writeErrors.length > 0; - } - - /** - * Returns the number of write errors off the bulk operation - * - * @return {Number} - * @api public - */ - this.getWriteErrorCount = function() { - return bulkResult.writeErrors.length; - } - - /** - * Returns a specific write error object - * - * @return {WriteError} - * @api public - */ - this.getWriteErrorAt = function(index) { - if(index < bulkResult.writeErrors.length) { - return bulkResult.writeErrors[index]; - } - return null; - } - - /** - * Retrieve all write errors - * - * @return {Array} - * @api public - */ - this.getWriteErrors = function() { - return bulkResult.writeErrors; - } - - /** - * Retrieve lastOp if available - * - * @return {Array} - * @api public - */ - this.getLastOp = function() { - return bulkResult.lastOp; - } - - /** - * Retrieve the write concern error if any - * - * @return {WriteConcernError} - * @api public - */ - this.getWriteConcernError = function() { - if(bulkResult.writeConcernErrors.length == 0) { - return null; - } else if(bulkResult.writeConcernErrors.length == 1) { - // Return the error - return bulkResult.writeConcernErrors[0]; - } else { - - // Combine the errors - var errmsg = ""; - for(var i = 0; i < bulkResult.writeConcernErrors.length; i++) { - var err = bulkResult.writeConcernErrors[i]; - errmsg = errmsg + err.errmsg; - - // TODO: Something better - if(i == 0) errmsg = errmsg + " and "; - } - - return new WriteConcernError({ errmsg : errmsg, code : WRITE_CONCERN_ERROR }); - } - } - - this.toJSON = function() { - return bulkResult; - } - - this.toString = function() { - return "BatchWriteResult(" + this.toJSON(bulkResult) + ")"; - } - - this.isOk = function() { - return bulkResult.ok == 1; - } -} - -/** - * Wraps a write concern error - */ -var WriteConcernError = function(err) { - if(!(this instanceof WriteConcernError)) return new WriteConcernError(err); - - // Define properties - defineReadOnlyProperty(this, "code", err.code); - defineReadOnlyProperty(this, "errmsg", err.errmsg); - - this.toJSON = function() { - return {code: err.code, errmsg: err.errmsg}; - } - - this.toString = function() { - return "WriteConcernError(" + err.errmsg + ")"; - } -} - -/** - * Wraps the error - */ -var WriteError = function(err) { - if(!(this instanceof WriteError)) return new WriteError(err); - - // Define properties - defineReadOnlyProperty(this, "code", err.code); - defineReadOnlyProperty(this, "index", err.index); - defineReadOnlyProperty(this, "errmsg", err.errmsg); - - // - // Define access methods - this.getOperation = function() { - return err.op; - } - - this.toJSON = function() { - return {code: err.code, index: err.index, errmsg: err.errmsg, op: err.op}; - } - - this.toString = function() { - return "WriteError(" + JSON.stringify(this.toJSON()) + ")"; - } -} - -/** - * Merges results into shared data structure - */ -var mergeBatchResults = function(ordered, batch, bulkResult, err, result) { - // If we have an error set the result to be the err object - if(err) { - result = err; - } - - // Do we have a top level error stop processing and return - if(result.ok == 0 && bulkResult.ok == 1) { - bulkResult.ok = 0; - bulkResult.error = utils.toError(result); - return; - } else if(result.ok == 0 && bulkResult.ok == 0) { - return; - } - - // Add lastop if available - if(result.lastOp) { - bulkResult.lastOp = result.lastOp; - } - - // If we have an insert Batch type - if(batch.batchType == INSERT && result.n) { - bulkResult.nInserted = bulkResult.nInserted + result.n; - } - - // If we have an insert Batch type - if(batch.batchType == REMOVE && result.n) { - bulkResult.nRemoved = bulkResult.nRemoved + result.n; - } - - var nUpserted = 0; - - // We have an array of upserted values, we need to rewrite the indexes - if(Array.isArray(result.upserted)) { - nUpserted = result.upserted.length; - - for(var i = 0; i < result.upserted.length; i++) { - bulkResult.upserted.push({ - index: result.upserted[i].index + batch.originalZeroIndex - , _id: result.upserted[i]._id - }); - } - } else if(result.upserted) { - - nUpserted = 1; - - bulkResult.upserted.push({ - index: batch.originalZeroIndex - , _id: result.upserted - }); - } - - // If we have an update Batch type - if(batch.batchType == UPDATE && result.n) { - var nModified = result.nModified; - bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; - bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); - - if(typeof nModified == 'number') { - bulkResult.nModified = bulkResult.nModified + nModified; - } else { - bulkResult.nModified = null; - } - } - - if(Array.isArray(result.writeErrors)) { - for(var i = 0; i < result.writeErrors.length; i++) { - - var writeError = { - index: batch.originalZeroIndex + result.writeErrors[i].index - , code: result.writeErrors[i].code - , errmsg: result.writeErrors[i].errmsg - , op: batch.operations[result.writeErrors[i].index] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - } - } - - if(result.writeConcernError) { - bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); - } -} - -// -// Merge a legacy result into the master results -var mergeLegacyResults = function(_ordered, _op, _batch, _results, _result, _index) { - // If we have an error already - if(_results.ok == 0) return false; - // Handle error - if((_result.errmsg || _result.err || _result instanceof Error) && _result.wtimeout != true) { - // && ((_result.wtimeout == null && _result.jnote == null && _result.wnote == null)) || _result.err == "norepl") { - var code = _result.code || UNKNOWN_ERROR; // Returned error code or unknown code - var errmsg = _result.errmsg || _result.err; - errmsg = errmsg || _result.message; - - // Result is replication issue, rewrite error to match write command - if(_result.wnote || _result.wtimeout || _result.jnote) { - // Set the code to replication error - code = WRITE_CONCERN_ERROR; - // Ensure we get the right error message - errmsg = _result.wnote || errmsg; - errmsg = _result.jnote || errmsg; - } - - // - // We have an error that is a show stopper, 16544 and 13 are auth errors that should stop processing - if(_result.wnote - || _result.jnote == "journaling not enabled on this server" - || _result.err == "norepl" - || _result.code == 16544 - || _result.code == 13) { - _results.ok = 0; - _results.error = utils.toError({code: code, errmsg: errmsg}); - return false; - } - - // Create a write error - var errResult = new WriteError({ - index: _index - , code: code - , errmsg: errmsg - , op: _op - }); - - // Err details - _results.writeErrors.push(errResult); - - // Check if we any errors - if(_ordered == true - && _result.jnote == null - && _result.wnote == null - && _result.wtimeout == null) { - return false; - } - } else if(_batch.batchType == INSERT) { - _results.nInserted = _results.nInserted + 1; - } else if(_batch.batchType == UPDATE) { - // If we have an upserted value or if the user provided a custom _id value - if(_result.upserted || (!_result.updatedExisting && _result.upserted == null)) { - _results.nUpserted = _results.nUpserted + 1; - } else { - _results.nMatched = _results.nMatched + _result.n; - _results.nModified = null; - } - } else if(_batch.batchType == REMOVE) { - _results.nRemoved = _results.nRemoved + _result; - } - - // We have a write concern error, add a write concern error to the results - if(_result.wtimeout != null || _result.jnote != null || _result.wnote != null) { - var error = _result.err || _result.errmsg || _result.wnote || _result.jnote || _result.wtimeout; - var code = _result.code || WRITE_CONCERN_ERROR; - // Push a write concern error to the list - _results.writeConcernErrors.push(new WriteConcernError({errmsg: error, code: code})); - } - - // We have an upserted field (might happen with a write concern error) - if(_result.upserted) { - _results.upserted.push({ - index: _index - , _id: _result.upserted - }) - } else if(!_result.updatedExisting && _result.upserted == null && _op.q && _op.q._id) { - _results.upserted.push({ - index: _index - , _id: _op.q._id - }) - } -} - -// -// Clone the options -var cloneOptions = function(options) { - var clone = {}; - var keys = Object.keys(options); - for(var i = 0; i < keys.length; i++) { - clone[keys[i]] = options[keys[i]]; - } - - return clone; -} - -// Exports symbols -exports.BatchWriteResult = BatchWriteResult; -exports.WriteError = WriteError; -exports.Batch = Batch; -exports.LegacyOp = LegacyOp; -exports.mergeBatchResults = mergeBatchResults; -exports.cloneOptions = cloneOptions; -exports.mergeLegacyResults = mergeLegacyResults; -exports.INVALID_BSON_ERROR = INVALID_BSON_ERROR; -exports.WRITE_CONCERN_ERROR = WRITE_CONCERN_ERROR; -exports.MULTIPLE_ERROR = MULTIPLE_ERROR; -exports.UNKNOWN_ERROR = UNKNOWN_ERROR; -exports.INSERT = INSERT; -exports.UPDATE = UPDATE; -exports.REMOVE = REMOVE; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js deleted file mode 100755 index 6fe275f5..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js +++ /dev/null @@ -1,530 +0,0 @@ -var shared = require('../shared') - , common = require('./common') - , utils = require('../../utils') - , hasWriteCommands = utils.hasWriteCommands - , WriteError = common.WriteError - , BatchWriteResult = common.BatchWriteResult - , LegacyOp = common.LegacyOp - , ObjectID = require('bson').ObjectID - , Batch = common.Batch - , mergeBatchResults = common.mergeBatchResults; - -/** - * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - * @class Represents a OrderedBulkOperation - * @param {Object} collection collection instance. - * @param {Object} [options] additional options for the collection. - * @return {Object} a ordered bulk operation instance. - */ -function OrderedBulkOperation (collection, options) { - options = options == null ? {} : options; - // TODO Bring from driver information in isMaster - var self = this; - var executed = false; - - // Current item - var currentOp = null; - - // Handle to the bson serializer, used to calculate running sizes - var db = collection.db; - var bson = db.bson; - - // Namespace for the operation - var namespace = collection.collectionName; - - // Set max byte size - var maxWriteBatchSize = db.serverConfig.checkoutWriter().maxWriteBatchSize || 1000; - var maxBatchSizeBytes = db.serverConfig.checkoutWriter().maxBsonSize; - - // Get the write concern - var writeConcern = shared._getWriteConcern(collection, options); - - // Current batch - var currentBatch = null; - var currentIndex = 0; - var currentBatchSize = 0; - var currentBatchSizeBytes = 0; - var batches = []; - - // Final results - var bulkResult = { - ok: 1 - , writeErrors: [] - , writeConcernErrors: [] - , nInserted: 0 - , nUpserted: 0 - , nMatched: 0 - , nModified: 0 - , nRemoved: 0 - , upserted: [] - }; - - // Specify a full class so we can generate documentation correctly - var FindOperators = function() { - /** - * Add a single update document to the bulk operation - * - * @param {Object} doc update operations - * @return {OrderedBulkOperation} - * @api public - */ - this.update = function(updateDocument) { - // Perform upsert - var upsert = typeof currentOp.upsert == 'boolean' ? currentOp.upsert : false; - - // Establish the update command - var document = { - q: currentOp.selector - , u: updateDocument - , multi: true - , upsert: upsert - } - - // Clear out current Op - currentOp = null; - // Add the update document to the list - return addToOperationsList(self, common.UPDATE, document); - } - - /** - * Add a single update one document to the bulk operation - * - * @param {Object} doc update operations - * @return {OrderedBulkOperation} - * @api public - */ - this.updateOne = function(updateDocument) { - // Perform upsert - var upsert = typeof currentOp.upsert == 'boolean' ? currentOp.upsert : false; - - // Establish the update command - var document = { - q: currentOp.selector - , u: updateDocument - , multi: false - , upsert: upsert - } - - // Clear out current Op - currentOp = null; - // Add the update document to the list - return addToOperationsList(self, common.UPDATE, document); - } - - /** - * Add a replace one operation to the bulk operation - * - * @param {Object} doc the new document to replace the existing one with - * @return {OrderedBulkOperation} - * @api public - */ - this.replaceOne = function(updateDocument) { - this.updateOne(updateDocument); - } - - /** - * Upsert modifier for update bulk operation - * - * @return {OrderedBulkOperation} - * @api public - */ - this.upsert = function() { - currentOp.upsert = true; - return this; - } - - /** - * Add a remove one operation to the bulk operation - * - * @param {Object} doc selector for the removal of documents - * @return {OrderedBulkOperation} - * @api public - */ - this.removeOne = function() { - // Establish the update command - var document = { - q: currentOp.selector - , limit: 1 - } - - // Clear out current Op - currentOp = null; - // Add the remove document to the list - return addToOperationsList(self, common.REMOVE, document); - } - - /** - * Add a remove operation to the bulk operation - * - * @param {Object} doc selector for the single document to remove - * @return {OrderedBulkOperation} - * @api public - */ - this.remove = function() { - // Establish the update command - var document = { - q: currentOp.selector - , limit: 0 - } - - // Clear out current Op - currentOp = null; - // Add the remove document to the list - return addToOperationsList(self, common.REMOVE, document); - } - } - - /** - * Add a single insert document to the bulk operation - * - * @param {Object} doc the document to insert - * @return {OrderedBulkOperation} - * @api public - */ - this.insert = function(document) { - if(document._id == null) document._id = new ObjectID(); - return addToOperationsList(self, common.INSERT, document); - } - - var getOrderedCommand = function(_self, _namespace, _docType, _operationDocuments) { - // Set up the types of operation - if(_docType == common.INSERT) { - return { - insert: _namespace - , documents: _operationDocuments - , ordered:true - } - } else if(_docType == common.UPDATE) { - return { - update: _namespace - , updates: _operationDocuments - , ordered:true - }; - } else if(_docType == common.REMOVE) { - return { - delete: _namespace - , deletes: _operationDocuments - , ordered:true - }; - } - } - - // Add to internal list of documents - var addToOperationsList = function(_self, docType, document) { - // Get the bsonSize - var bsonSize = bson.calculateObjectSize(document, false); - // Throw error if the doc is bigger than the max BSON size - if(bsonSize >= maxBatchSizeBytes) throw utils.toError("document is larger than the maximum size " + maxBatchSizeBytes); - // Create a new batch object if we don't have a current one - if(currentBatch == null) currentBatch = new Batch(docType, currentIndex); - - // Check if we need to create a new batch - if(((currentBatchSize + 1) >= maxWriteBatchSize) - || ((currentBatchSizeBytes + currentBatchSizeBytes) >= maxBatchSizeBytes) - || (currentBatch.batchType != docType)) { - // Save the batch to the execution stack - batches.push(currentBatch); - - // Create a new batch - currentBatch = new Batch(docType, currentIndex); - - // Reset the current size trackers - currentBatchSize = 0; - currentBatchSizeBytes = 0; - } else { - // Update current batch size - currentBatchSize = currentBatchSize + 1; - currentBatchSizeBytes = currentBatchSizeBytes + bsonSize; - } - - // We have an array of documents - if(Array.isArray(document)) { - throw utils.toError("operation passed in cannot be an Array"); - } else { - currentBatch.originalIndexes.push(currentIndex); - currentBatch.operations.push(document) - currentIndex = currentIndex + 1; - } - - // Return self - return _self; - } - - /** - * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne - * - * @param {Object} doc - * @return {OrderedBulkOperation} - * @api public - */ - this.find = function(selector) { - if (!selector) { - throw utils.toError("Bulk find operation must specify a selector"); - } - - // Save a current selector - currentOp = { - selector: selector - } - - return new FindOperators(); - } - - // - // Execute next write command in a chain - var executeCommands = function(callback) { - if(batches.length == 0) { - return callback(null, new BatchWriteResult(bulkResult)); - } - - // Ordered execution of the command - var batch = batches.shift(); - - // Build the command - var cmd = null; - - // Generate the right update - if(batch.batchType == common.UPDATE) { - cmd = { update: namespace, updates: batch.operations, ordered: true } - } else if(batch.batchType == common.INSERT) { - cmd = { insert: namespace, documents: batch.operations, ordered: true } - } else if(batch.batchType == common.REMOVE) { - cmd = { delete: namespace, deletes: batch.operations, ordered: true } - } - - // If we have a write concern - if(writeConcern != null) { - cmd.writeConcern = writeConcern; - } - - // Execute it - db.command(cmd, function(err, result) { - // Merge the results together - var mergeResult = mergeBatchResults(true, batch, bulkResult, err, result); - if(mergeResult != null) { - return callback(null, new BatchWriteResult(bulkResult)); - } - - // If we had a serious error - if(bulkResult.ok == 0) { - return callback(bulkResult.error, null); - } - - // If we are ordered and have errors and they are - // not all replication errors terminate the operation - if(bulkResult.writeErrors.length > 0) { - return callback(null, new BatchWriteResult(bulkResult)); - } - - // Execute the next command in line - executeCommands(callback); - }); - } - - // - // Execute the inserts - var executeInserts = function(_collection, _batch, _result, _callback) { - if(_batch.operations.length == 0) { - return _callback(null, _result); - } - - // Get the first update - var document = _batch.operations.shift(); - var index = _batch.originalIndexes.shift(); - - // Options for the update operation - var options = writeConcern || {}; - - // Execute the update - _collection.insert(document, options, function(err, r) { - // If we have don't have w:0 merge the result - if(options.w == null || options.w != 0) { - // Merge the results in - var result = common.mergeLegacyResults(true, document, _batch, bulkResult, err || r, index); - - if(result == false) { - return _callback(null, new BatchWriteResult(bulkResult)); - } - } - - // Update the index - _batch.currentIndex = _batch.currentIndex + 1; - - // Execute the next insert - executeInserts(_collection, _batch, _result, _callback); - }); - } - - // - // Execute updates - var executeUpdates = function(_collection, _batch, _result, _callback) { - if(_batch.operations.length == 0) { - return _callback(null, _result); - } - - // Get the first update - var update = _batch.operations.shift(); - var index = _batch.originalIndexes.shift(); - - // Options for the update operation - var options = writeConcern != null ? common.cloneOptions(writeConcern) : {}; - - // Add any additional options - if(update.multi) options.multi = update.multi; - if(update.upsert) options.upsert = update.upsert; - - // Execute the update - _collection.update(update.q, update.u, options, function(err, r, full) { - // If we have don't have w:0 merge the result - if(options.w == null || options.w != 0) { - // Merge the results in - var result = common.mergeLegacyResults(true, update, _batch, bulkResult, err || full, index); - if(result == false) { - return _callback(null, new BatchWriteResult(bulkResult)); - } - } - - // Update the index - _batch.currentIndex = _batch.currentIndex + 1; - - // Execute the next insert - executeUpdates(_collection, _batch, _result, _callback); - }); - } - - // - // Execute updates - var executeRemoves = function(_collection, _batch, _result, _callback) { - if(_batch.operations.length == 0) { - return _callback(null, _result); - } - - // Get the first update - var remove = _batch.operations.shift(); - var index = _batch.originalIndexes.shift(); - - // Options for the update operation - var options = writeConcern != null ? common.cloneOptions(writeConcern) : {}; - - // Add any additional options - options.single = remove.limit == 1 ? true : false; - - // Execute the update - _collection.remove(remove.q, options, function(err, r) { - // If we have don't have w:0 merge the result - if(options.w == null || options.w != 0) { - // Merge the results in - var result = common.mergeLegacyResults(true, remove, _batch, bulkResult, err || r, index); - if(result == false) { - return _callback(null, new BatchWriteResult(bulkResult)); - } - } - - // Update the index - _batch.currentIndex = _batch.currentIndex + 1; - - // Execute the next insert - executeRemoves(_collection, _batch, _result, _callback); - }); - } - - // - // Execute all operation in backwards compatible fashion - var backwardsCompatibilityExecuteCommands = function(callback) { - if(batches.length == 0) { - return callback(null, new BatchWriteResult(bulkResult)); - } - - // Ordered execution of the command - var batch = batches.shift(); - - // Process the legacy operations - var processLegacyOperations = function(err, results) { - // If we have any errors stop executing - if(bulkResult.writeErrors.length > 0) { - return callback(null, new BatchWriteResult(bulkResult)); - } - - // If we have a top level error stop - if(bulkResult.ok == 0) { - return callback(bulkResult.error, null); - } - - // Execute the next step - backwardsCompatibilityExecuteCommands(callback); - } - - // Execute an insert batch - if(batch.batchType == common.INSERT) { - return executeInserts(collection, batch, {n: 0}, processLegacyOperations); - } - - // Execute an update batch - if(batch.batchType == common.UPDATE) { - return executeUpdates(collection, batch, {n: 0}, processLegacyOperations); - } - - // Execute an update batch - if(batch.batchType == common.REMOVE) { - return executeRemoves(collection, batch, {n: 0}, processLegacyOperations); - } - } - - /** - * Execute the ordered bulk operation - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from from the ordered bulk operation. - * @return {null} - * @api public - */ - this.execute = function(_writeConcern, callback) { - if(executed) throw new utils.toError("batch cannot be re-executed"); - if(typeof _writeConcern == 'function') { - callback = _writeConcern; - } else { - writeConcern = _writeConcern; - } - - // If we have current batch - if(currentBatch) batches.push(currentBatch); - - // If we have no operations in the bulk raise an error - if(batches.length == 0) { - throw utils.toError("Invalid Operation, No operations in bulk"); - } - - // Check if we support bulk commands, override if needed to use legacy ops - if(hasWriteCommands(db.serverConfig.checkoutWriter())) - return executeCommands(callback); - - // Set nModified to null as we don't support this field - bulkResult.nModified = null; - - // Run in backward compatibility mode - backwardsCompatibilityExecuteCommands(callback); - } -} - -/** - * Returns an unordered batch object - * - */ -var initializeOrderedBulkOp = function(options) { - return new OrderedBulkOperation(this, options); -} - -exports.initializeOrderedBulkOp = initializeOrderedBulkOp; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js deleted file mode 100755 index f62ccdb4..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js +++ /dev/null @@ -1,553 +0,0 @@ -var shared = require('../shared') - , common = require('./common') - , utils = require('../../utils') - , hasWriteCommands = utils.hasWriteCommands - , WriteError = common.WriteError - , BatchWriteResult = common.BatchWriteResult - , LegacyOp = common.LegacyOp - , ObjectID = require('bson').ObjectID - , Batch = common.Batch - , mergeBatchResults = common.mergeBatchResults; - -/** - * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - * @class Represents a UnorderedBulkOperation - * @param {Object} collection collection instance. - * @param {Object} [options] additional options for the collection. - * @return {Object} a ordered bulk operation instance. - */ -var UnorderedBulkOperation = function(collection, options) { - options = options == null ? {} : options; - - // Contains reference to self - var self = this; - // Get the namesspace for the write operations - var namespace = collection.collectionName; - // Used to mark operation as executed - var executed = false; - - // Current item - var currentOp = null; - var currentIndex = 0; - var batches = []; - - // The current Batches for the different operations - var currentInsertBatch = null; - var currentUpdateBatch = null; - var currentRemoveBatch = null; - - // Handle to the bson serializer, used to calculate running sizes - var db = collection.db; - var bson = db.bson; - - // Set max byte size - var maxBatchSizeBytes = db.serverConfig.checkoutWriter().maxBsonSize; - var maxWriteBatchSize = db.serverConfig.checkoutWriter().maxWriteBatchSize || 1000; - - // Get the write concern - var writeConcern = shared._getWriteConcern(collection, options); - - // Final results - var bulkResult = { - ok: 1 - , writeErrors: [] - , writeConcernErrors: [] - , nInserted: 0 - , nUpserted: 0 - , nMatched: 0 - , nModified: 0 - , nRemoved: 0 - , upserted: [] - }; - - // Specify a full class so we can generate documentation correctly - var FindOperators = function() { - /** - * Add a single update document to the bulk operation - * - * @param {Object} doc update operations - * @return {UnorderedBulkOperation} - * @api public - */ - this.update = function(updateDocument) { - // Perform upsert - var upsert = typeof currentOp.upsert == 'boolean' ? currentOp.upsert : false; - - // Establish the update command - var document = { - q: currentOp.selector - , u: updateDocument - , multi: true - , upsert: upsert - } - - // Clear out current Op - currentOp = null; - // Add the update document to the list - return addToOperationsList(self, common.UPDATE, document); - } - - /** - * Add a single update one document to the bulk operation - * - * @param {Object} doc update operations - * @return {UnorderedBulkOperation} - * @api public - */ - this.updateOne = function(updateDocument) { - // Perform upsert - var upsert = typeof currentOp.upsert == 'boolean' ? currentOp.upsert : false; - - // Establish the update command - var document = { - q: currentOp.selector - , u: updateDocument - , multi: false - , upsert: upsert - } - - // Clear out current Op - currentOp = null; - // Add the update document to the list - return addToOperationsList(self, common.UPDATE, document); - } - - /** - * Add a replace one operation to the bulk operation - * - * @param {Object} doc the new document to replace the existing one with - * @return {UnorderedBulkOperation} - * @api public - */ - this.replaceOne = function(updateDocument) { - this.updateOne(updateDocument); - } - - /** - * Upsert modifier for update bulk operation - * - * @return {UnorderedBulkOperation} - * @api public - */ - this.upsert = function() { - currentOp.upsert = true; - return this; - } - - /** - * Add a remove one operation to the bulk operation - * - * @param {Object} doc selector for the removal of documents - * @return {UnorderedBulkOperation} - * @api public - */ - this.removeOne = function() { - // Establish the update command - var document = { - q: currentOp.selector - , limit: 1 - } - - // Clear out current Op - currentOp = null; - // Add the remove document to the list - return addToOperationsList(self, common.REMOVE, document); - } - - /** - * Add a remove operation to the bulk operation - * - * @param {Object} doc selector for the single document to remove - * @return {UnorderedBulkOperation} - * @api public - */ - this.remove = function() { - // Establish the update command - var document = { - q: currentOp.selector - , limit: 0 - } - - // Clear out current Op - currentOp = null; - // Add the remove document to the list - return addToOperationsList(self, common.REMOVE, document); - } - } - - // - // Add to the operations list - // - var addToOperationsList = function(_self, docType, document) { - // Get the bsonSize - var bsonSize = bson.calculateObjectSize(document, false); - // Throw error if the doc is bigger than the max BSON size - if(bsonSize >= maxBatchSizeBytes) throw utils.toError("document is larger than the maximum size " + maxBatchSizeBytes); - // Holds the current batch - var currentBatch = null; - // Get the right type of batch - if(docType == common.INSERT) { - currentBatch = currentInsertBatch; - } else if(docType == common.UPDATE) { - currentBatch = currentUpdateBatch; - } else if(docType == common.REMOVE) { - currentBatch = currentRemoveBatch; - } - - // Create a new batch object if we don't have a current one - if(currentBatch == null) currentBatch = new Batch(docType, currentIndex); - - // Check if we need to create a new batch - if(((currentBatch.size + 1) >= maxWriteBatchSize) - || ((currentBatch.sizeBytes + bsonSize) >= maxBatchSizeBytes) - || (currentBatch.batchType != docType)) { - // Save the batch to the execution stack - batches.push(currentBatch); - - // Create a new batch - currentBatch = new Batch(docType, currentIndex); - } - - // We have an array of documents - if(Array.isArray(document)) { - throw utils.toError("operation passed in cannot be an Array"); - } else { - currentBatch.operations.push(document); - currentBatch.originalIndexes.push(currentIndex); - currentIndex = currentIndex + 1; - } - - // Save back the current Batch to the right type - if(docType == common.INSERT) { - currentInsertBatch = currentBatch; - } else if(docType == common.UPDATE) { - currentUpdateBatch = currentBatch; - } else if(docType == common.REMOVE) { - currentRemoveBatch = currentBatch; - } - - // Update current batch size - currentBatch.size = currentBatch.size + 1; - currentBatch.sizeBytes = currentBatch.sizeBytes + bsonSize; - - // Return self - return _self; - } - - /** - * Add a single insert document to the bulk operation - * - * @param {Object} doc the document to insert - * @return {UnorderedBulkOperation} - * @api public - */ - this.insert = function(document) { - if(document._id == null) document._id = new ObjectID(); - return addToOperationsList(self, common.INSERT, document); - } - - /** - * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne - * - * @param {Object} selector the selector used to locate documents for the operation - * @return {UnorderedBulkOperation} - * @api public - */ - this.find = function(selector) { - if (!selector) { - throw utils.toError("Bulk find operation must specify a selector"); - } - - // Save a current selector - currentOp = { - selector: selector - } - - return new FindOperators(); - } - - // - // Execute the command - var executeBatch = function(batch, callback) { - // Contains the command we are going to execute - var cmd = null; - - // Generate the right update - if(batch.batchType == common.UPDATE) { - cmd = { update: namespace, updates: batch.operations, ordered: false } - } else if(batch.batchType == common.INSERT) { - cmd = { insert: namespace, documents: batch.operations, ordered: false } - } else if(batch.batchType == common.REMOVE) { - cmd = { delete: namespace, deletes: batch.operations, ordered: false } - } - - // If we have a write concern - if(writeConcern != null) { - cmd.writeConcern = writeConcern; - } - - // Execute the write command - db.command(cmd, function(err, result) { - callback(null, mergeBatchResults(false, batch, bulkResult, err, result)); - }); - } - - // - // Execute all the commands - var executeBatches = function(callback) { - var numberOfCommandsToExecute = batches.length; - // Execute over all the batches - for(var i = 0; i < batches.length; i++) { - executeBatch(batches[i], function(err, result) { - numberOfCommandsToExecute = numberOfCommandsToExecute - 1; - - // Execute - if(numberOfCommandsToExecute == 0) { - // If we have an error stop - if(bulkResult.ok == 0 && callback) { - return callback(bulkResult.error, null); - } - - callback(null, new BatchWriteResult(bulkResult)); - } - }); - } - } - - /** - * Execute the unordered bulk operation - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from from the unordered bulk operation. - * @return {null} - * @api public - */ - this.execute = function(_writeConcern, callback) { - if(executed) throw utils.toError("batch cannot be re-executed"); - if(typeof _writeConcern == 'function') { - callback = _writeConcern; - } else { - writeConcern = _writeConcern; - } - - // If we have current batch - if(currentInsertBatch) batches.push(currentInsertBatch); - if(currentUpdateBatch) batches.push(currentUpdateBatch); - if(currentRemoveBatch) batches.push(currentRemoveBatch); - - // If we have no operations in the bulk raise an error - if(batches.length == 0) { - throw utils.toError("Invalid Operation, No operations in bulk"); - } - - // Check if we support bulk commands - if(hasWriteCommands(db.serverConfig.checkoutWriter())) - return executeBatches(function(err, result) { - callback(err, result); - }); - - // Set nModified to null as we don't support this field - bulkResult.nModified = null; - - // Run in backward compatibility mode - backwardsCompatibilityExecuteCommands(function(err, result) { - callback(err, result); - }); - } - - // - // Execute the inserts - var executeInserts = function(_collection, _batch, _result, _callback) { - var totalNumberOfInserts = _batch.operations.length; - - // Options for the update operation - var batchOptions = writeConcern || {}; - - // Execute the op - var executeLegacyInsert = function(_i, _op, _options, __callback) { - // Execute the update - _collection.insert(_op.operation, _options, function(err, r) { - // If we have don't have w:0 merge the result - if(_options.w == null || _options.w != 0) { - // Merge the results in - var result = common.mergeLegacyResults(false, _op.operation, _batch, bulkResult, err || r, _op.index); - if(result == false) { - return _callback(null, new BatchWriteResult(bulkResult)); - } - } - - __callback(null, _result); - }); - } - - // Execute all the insert operations - for(var i = 0; i < _batch.operations.length; i++) { - var legacyOp = new LegacyOp(_batch.batchType, _batch.operations[i], _batch.originalIndexes[i]); - executeLegacyInsert(i, legacyOp, batchOptions, function(err, result) { - totalNumberOfInserts = totalNumberOfInserts - 1; - - // No more inserts - if(totalNumberOfInserts == 0) { - _callback(null, _result); - } - }); - } - } - - // - // Execute updates - var executeUpdates = function(_collection, _batch, _result, _callback) { - var totalNumberOfUpdates = _batch.operations.length; - // Options for the update operation - var batchOptions = writeConcern || {}; - - // Execute the op - var executeLegacyUpdate = function(_i, _op, _options, __callback) { - var options = common.cloneOptions(batchOptions); - - // Add any additional options - if(_op.operation.multi != null) options.multi = _op.operation.multi ? true : false; - if(_op.operation.upsert != null) options.upsert = _op.operation.upsert; - - // Execute the update - _collection.update(_op.operation.q, _op.operation.u, options, function(err, r, full) { - // If we have don't have w:0 merge the result - if(options.w == null || options.w != 0) { - // Merge the results in - var result = common.mergeLegacyResults(false, _op.operation, _batch, bulkResult, err || full, _op.index); - if(result == false) { - return _callback(null, new BatchWriteResult(bulkResult)); - } - } - - return __callback(null, _result); - }); - } - - // Execute all the insert operations - for(var i = 0; i < _batch.operations.length; i++) { - var legacyOp = new LegacyOp(_batch.batchType, _batch.operations[i], _batch.originalIndexes[i]); - executeLegacyUpdate(i, legacyOp, options, function(err, result) { - totalNumberOfUpdates = totalNumberOfUpdates - 1; - - // No more inserts - if(totalNumberOfUpdates == 0) { - _callback(null, _result); - } - }); - } - } - - // - // Execute updates - var executeRemoves = function(_collection, _batch, _result, _callback) { - var totalNumberOfRemoves = _batch.operations.length; - // Options for the update operation - var batchOptions = writeConcern || {}; - - // Execute the op - var executeLegacyRemove = function(_i, _op, _options, __callback) { - var options = common.cloneOptions(batchOptions); - - // Add any additional options - if(_op.operation.limit != null) options.single = _op.operation.limit == 1 ? true : false; - - // Execute the update - _collection.remove(_op.operation.q, options, function(err, r) { - // If we have don't have w:0 merge the result - if(options.w == null || options.w != 0) { - // Merge the results in - var result = common.mergeLegacyResults(false, _op.operation, _batch, bulkResult, err || r, _op.index); - if(result == false) { - return _callback(null, new BatchWriteResult(bulkResult)); - } - } - - return __callback(null, _result); - }); - } - - // Execute all the insert operations - for(var i = 0; i < _batch.operations.length; i++) { - var legacyOp = new LegacyOp(_batch.batchType, _batch.operations[i], _batch.originalIndexes[i]); - executeLegacyRemove(i, legacyOp, options, function(err, result) { - totalNumberOfRemoves = totalNumberOfRemoves - 1; - - // No more inserts - if(totalNumberOfRemoves == 0) { - _callback(null, _result); - } - }); - } - } - - // - // Execute all operation in backwards compatible fashion - var backwardsCompatibilityExecuteCommands = function(callback) { - if(batches.length == 0) { - return callback(null, new BatchWriteResult(bulkResult)); - } - - // Ordered execution of the command - var batch = batches.shift(); - - // Process the legacy operations - var processLegacyOperations = function(err, results) { - // Merge the results together - var mergeResult = mergeBatchResults(false, batch, bulkResult, err, results); - if(mergeResult != null) { - return callback(null, mergeResult) - } - - // If we have an error stop - if(bulkResult.ok == 0 && callback) { - var internalCallback = callback; - callback = null; - return internalCallback(bulkResult.error, null); - } else if(bulkResult.ok == 0 && callback == null) { - return; - } - - // Execute the next step - backwardsCompatibilityExecuteCommands(callback); - } - - // Execute an insert batch - if(batch.batchType == common.INSERT) { - return executeInserts(collection, batch, {n: 0}, processLegacyOperations); - } - - // Execute an update batch - if(batch.batchType == common.UPDATE) { - return executeUpdates(collection, batch, {n: 0}, processLegacyOperations); - } - - // Execute an update batch - if(batch.batchType == common.REMOVE) { - return executeRemoves(collection, batch, {n: 0}, processLegacyOperations); - } - } -} - -/** - * Returns an unordered batch object - * - */ -var initializeUnorderedBulkOp = function(options) { - return new UnorderedBulkOperation(this, options); -} - -exports.initializeUnorderedBulkOp = initializeUnorderedBulkOp; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/commands.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/commands.js deleted file mode 100755 index 7e784026..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/commands.js +++ /dev/null @@ -1,139 +0,0 @@ -var shared = require('./shared') - , utils = require('../utils') - , f = require('util').format - , DbCommand = require('../commands/db_command').DbCommand; - -var stats = function stats(options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - collStats:this.collectionName, - } - - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - - // Ensure we have the right read preference inheritance - options.readPreference = shared._getReadConcern(this, options); - - // Execute the command - this.db.command(commandObject, options, callback); -} - -var count = function count(query, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - var skip = options.skip; - var limit = options.limit; - var hint = options.hint; - var maxTimeMS = options.maxTimeMS; - - // Final query - var cmd = { - 'count': this.collectionName - , 'query': query - , 'fields': null - }; - - // Add limit and skip if defined - if(typeof skip == 'number') cmd.skip = skip; - if(typeof limit == 'number') cmd.limit = limit; - if(hint) cmd.hint = hint; - - // Ensure we have the right read preference inheritance - options.readPreference = shared._getReadConcern(this, options); - - // Execute the command - this.db.command(cmd, options, function(err, result) { - if(err) return callback(err); - callback(null, result.n); - }); -}; - -var distinct = function distinct(key, query, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - var maxTimeMS = options.maxTimeMS; - - var cmd = { - 'distinct': this.collectionName - , 'key': key - , 'query': query - }; - - // Ensure we have the right read preference inheritance - options.readPreference = shared._getReadConcern(this, options); - - // Execute the command - this.db.command(cmd, options, function(err, result) { - if(err) return callback(err); - callback(null, result.values); - }); -}; - -var rename = function rename (newName, options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {} - } - - // Get collection class - var Collection = require('../collection').Collection; - // Ensure the new name is valid - shared.checkCollectionName(newName); - - // Build the command - var renameCollection = self.db.databaseName + "." + self.collectionName; - var toCollection = self.db.databaseName + "." + newName; - var dropTarget = typeof options.dropTarget == 'boolean' ? options.dropTarget : false; - var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}; - - // Execute against admin - self.db.admin().command(cmd, options, function(err, result) { - if(err) return callback(err, null); - var doc = result.documents[0]; - // We have an error - if(doc.errmsg) return callback(utils.toError(doc), null); - try { - return callback(null, new Collection(self.db, newName, self.db.pkFactory)); - } catch(err) { - return callback(utils.toError(err), null); - } - }); -}; - -var options = function options(callback) { - var self = this; - - self.db.listCollections({name: self.collectionName}).toArray(function(err, collections) { - if(err) return callback(err); - if(collections.length == 0) return callback(utils.toError(f("collection %s.%s not found", self.db.databaseName, self.collectionName))); - callback(err, collections[0].options || null); - }); -}; - -var isCapped = function isCapped(callback) { - this.options(function(err, document) { - if(err != null) { - callback(err); - } else { - callback(null, document && document.capped); - } - }); -}; - -exports.stats = stats; -exports.count = count; -exports.distinct = distinct; -exports.rename = rename; -exports.options = options; -exports.isCapped = isCapped; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/core.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/core.js deleted file mode 100755 index 5c2f7b0b..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/core.js +++ /dev/null @@ -1,811 +0,0 @@ -var InsertCommand = require('../commands/insert_command').InsertCommand - , DeleteCommand = require('../commands/delete_command').DeleteCommand - , UpdateCommand = require('../commands/update_command').UpdateCommand - , DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , hasWriteCommands = require('../utils').hasWriteCommands - , shared = require('./shared'); - -/** - * Precompiled regexes - * @ignore - **/ -var eErrorMessages = /No matching object found/; - -// *************************************************** -// Insert function -// *************************************************** -var insert = function insert (docs, options, callback) { - if ('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // Get a connection - var connection = this.db.serverConfig.checkoutWriter(); - if(connection instanceof Error && connection.code == -5000) return callback(connection); - var useLegacyOps = options.useLegacyOps == null || options.useLegacyOps == false ? false : true; - // If we support write commands let's perform the insert using it - if(!useLegacyOps && hasWriteCommands(connection) - && !Buffer.isBuffer(docs) - && !(Array.isArray(docs) && docs.length > 0 && Buffer.isBuffer(docs[0]))) { - insertWithWriteCommands(this, Array.isArray(docs) ? docs : [docs], options, callback); - return this - } - - // Backwards compatibility - insertAll(this, Array.isArray(docs) ? docs : [docs], options, callback); - return this; -}; - -// -// Uses the new write commands available from 2.6 > -// -var insertWithWriteCommands = function(self, docs, options, callback) { - // Get the intended namespace for the operation - var namespace = self.collectionName; - - // Ensure we have no \x00 bytes in the name causing wrong parsing - if(!!~namespace.indexOf("\x00")) { - return callback(new Error("namespace cannot contain a null character"), null); - } - - // Check if we have passed in continue on error - var continueOnError = typeof options['keepGoing'] == 'boolean' - ? options['keepGoing'] : false; - continueOnError = typeof options['continueOnError'] == 'boolean' - ? options['continueOnError'] : continueOnError; - - // Do we serialzie functions - var serializeFunctions = typeof options.serializeFunctions != 'boolean' - ? self.serializeFunctions : options.serializeFunctions; - - // Checkout a write connection - var connection = self.db.serverConfig.checkoutWriter(); - if(connection instanceof Error && connection.code == -5000) return callback(connection); - - // Do we return the actual result document - var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false; - - // Collect errorOptions - var errorOptions = shared._getWriteConcern(self, options); - - // If we have a write command with no callback and w:0 fail - if(errorOptions.w && errorOptions.w != 0 && callback == null) { - throw new Error("writeConcern requires callback") - } - - // Add the documents and decorate them with id's if they have none - for(var index = 0, len = docs.length; index < len; ++index) { - var doc = docs[index]; - - // Add id to each document if it's not already defined - if (!(Buffer.isBuffer(doc)) - && doc['_id'] == null - && self.db.forceServerObjectId != true - && options.forceServerObjectId != true) { - doc['_id'] = self.pkFactory.createPk(); - } - } - - // Single document write - if(docs.length == 1) { - // Create the write command - var write_command = { - insert: namespace - , writeConcern: errorOptions - , ordered: !continueOnError - , documents: docs - } - - // Execute the write command - return self.db.command(write_command - , { connection:connection - , checkKeys: typeof options.checkKeys == 'boolean' ? options.checkKeys : true - , serializeFunctions: serializeFunctions - , writeCommand: true } - , function(err, result) { - if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null); - if(errorOptions.w == 0) return; - if(callback == null) return; - if(err != null) { - return callback(err, null); - } - - // Result has an error - if(!result.ok || Array.isArray(result.writeErrors) && result.writeErrors.length > 0) { - var error = utils.toError(result.writeErrors[0].errmsg); - error.code = result.writeErrors[0].code; - error.err = result.writeErrors[0].errmsg; - error.message = result.writeErrors[0].errmsg; - - if (fullResult) return callback(error, result != null ? result : null); - // Return the error - return callback(error, null); - } - - if(fullResult) return callback(null, result); - // Return the results for a whole batch - callback(null, docs) - }); - } else { - try { - // Multiple document write (use bulk) - var bulk = !continueOnError ? self.initializeOrderedBulkOp() : self.initializeUnorderedBulkOp(); - // Add all the documents - for(var i = 0; i < docs.length;i++) { - bulk.insert(docs[i]); - } - - // Execute the command - bulk.execute(errorOptions, function(err, result) { - if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null); - if(errorOptions.w == 0) return; - if(callback == null) return; - if(err) return callback(err, null); - if(result.hasWriteErrors()) { - var error = result.getWriteErrors()[0]; - error.code = result.getWriteErrors()[0].code; - error.err = result.getWriteErrors()[0].errmsg; - error.message = result.getWriteErrors()[0].errmsg; - - if (fullResult) return callback(error, result != null ? result : null); - // Return the error - return callback(error, null); - } - - if(fullResult) return callback(null, result != null ? result : null); - // Return the results for a whole batch - callback(null, docs) - }); - } catch(err) { - callback(utils.toError(err), null); - } - } -} - -// -// Uses pre 2.6 OP_INSERT wire protocol -// -var insertAll = function insertAll (self, docs, options, callback) { - if('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // Insert options (flags for insert) - var insertFlags = {}; - // If we have a mongodb version >= 1.9.1 support keepGoing attribute - if(options['keepGoing'] != null) { - insertFlags['keepGoing'] = options['keepGoing']; - } - - // If we have a mongodb version >= 1.9.1 support keepGoing attribute - if(options['continueOnError'] != null) { - insertFlags['continueOnError'] = options['continueOnError']; - } - - // DbName - var dbName = options['dbName']; - // If no dbname defined use the db one - if(dbName == null) { - dbName = self.db.databaseName; - } - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - insertFlags['serializeFunctions'] = options['serializeFunctions']; - } else { - insertFlags['serializeFunctions'] = self.serializeFunctions; - } - - // Get checkKeys value - var checkKeys = typeof options.checkKeys != 'boolean' ? true : options.checkKeys; - - // Do we return the actual result document - var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false; - - // Pass in options - var insertCommand = new InsertCommand( - self.db - , dbName + "." + self.collectionName, checkKeys, insertFlags); - - // Add the documents and decorate them with id's if they have none - for(var index = 0, len = docs.length; index < len; ++index) { - var doc = docs[index]; - - // Add id to each document if it's not already defined - if (!(Buffer.isBuffer(doc)) - && doc['_id'] == null - && self.db.forceServerObjectId != true - && options.forceServerObjectId != true) { - doc['_id'] = self.pkFactory.createPk(); - } - - insertCommand.add(doc); - } - - // Collect errorOptions - var errorOptions = shared._getWriteConcern(self, options); - // Default command options - var commandOptions = {}; - // If safe is defined check for error message - if(shared._hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Set safe option - commandOptions['safe'] = errorOptions; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // If we have a passed in connection use it - if(options.connection) { - commandOptions.connection = options.connection; - } - - // Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection) - self.db._executeInsertCommand(insertCommand, commandOptions, handleWriteResults(function (err, results) { - if(err) return callback(err, null); - if(results == null) return callback(new Error("command failed to return result")); - if(fullResult) return callback(null, results); - callback(null, docs); - })); - } else if(shared._hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - // Execute the call without a write concern - var result = self.db._executeInsertCommand(insertCommand, commandOptions); - // If no callback just return - if(!callback) return; - // If error return error - if(result instanceof Error) { - return callback(result); - } - - // Otherwise just return - return callback(null, docs); - } -}; - -// *************************************************** -// Remove function -// *************************************************** -var removeWithWriteCommands = function(self, selector, options, callback) { - if('function' === typeof selector) { - callback = selector; - selector = options = {}; - } else if ('function' === typeof options) { - callback = options; - options = {}; - } - - // Get the intended namespace for the operation - var namespace = self.collectionName; - - // Ensure we have no \x00 bytes in the name causing wrong parsing - if(!!~namespace.indexOf("\x00")) { - return callback(new Error("namespace cannot contain a null character"), null); - } - - // Set default empty selector if none - selector = selector == null ? {} : selector; - - // Check if we have passed in continue on error - var continueOnError = typeof options['keepGoing'] == 'boolean' - ? options['keepGoing'] : false; - continueOnError = typeof options['continueOnError'] == 'boolean' - ? options['continueOnError'] : continueOnError; - - // Do we serialzie functions - var serializeFunctions = typeof options.serializeFunctions != 'boolean' - ? self.serializeFunctions : options.serializeFunctions; - - // Checkout a write connection - var connection = self.db.serverConfig.checkoutWriter(); - if(connection instanceof Error && connection.code == -5000) return callback(connection); - - // Figure out the value of top - var limit = options.single == true ? 1 : 0; - var upsert = typeof options.upsert == 'boolean' ? options.upsert : false; - - // Do we return the actual result document - var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false; - - // Collect errorOptions - var errorOptions = shared._getWriteConcern(self, options); - - // If we have a write command with no callback and w:0 fail - if(errorOptions.w && errorOptions.w != 0 && callback == null) { - throw new Error("writeConcern requires callback") - } - - // Create the write command - var write_command = { - delete: namespace, - writeConcern: errorOptions, - ordered: !continueOnError, - deletes: [{ - q : selector, - limit: limit - }] - } - - // Execute the write command - self.db.command(write_command - , { connection:connection - , checkKeys: false - , serializeFunctions: serializeFunctions - , writeCommand: true } - , function(err, result) { - if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null); - if(errorOptions.w == 0) return; - if(callback == null) return; - if(err != null) { - return callback(err, null); - } - - // Result has an error - if(!result.ok || Array.isArray(result.writeErrors) && result.writeErrors.length > 0) { - var error = utils.toError(result.writeErrors[0].errmsg); - error.code = result.writeErrors[0].code; - error.err = result.writeErrors[0].errmsg; - error.message = result.writeErrors[0].errmsg; - // Return the error - return callback(error, null); - } - - if(fullResult) return callback(null, result); - // Backward compatibility format - var r = backWardsCompatibiltyResults(result, 'remove'); - // Return the results for a whole batch - callback(null, r.n, r) - }); -} - -var remove = function remove(selector, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // Get a connection - var connection = this.db.serverConfig.checkoutWriter(); - if(connection instanceof Error && connection.code == -5000) return callback(connection); - var useLegacyOps = options.useLegacyOps == null || options.useLegacyOps == false ? false : true; - - // If we support write commands let's perform the insert using it - if(!useLegacyOps && hasWriteCommands(connection) && !Buffer.isBuffer(selector)) { - return removeWithWriteCommands(this, selector, options, callback); - } - - if ('function' === typeof selector) { - callback = selector; - selector = options = {}; - } else if ('function' === typeof options) { - callback = options; - options = {}; - } - - // Ensure options - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - // Ensure we have at least an empty selector - selector = selector == null ? {} : selector; - // Set up flags for the command, if we have a single document remove - var flags = 0 | (options.single ? 1 : 0); - - // Do we return the actual result document - var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false; - - // DbName - var dbName = options['dbName']; - // If no dbname defined use the db one - if(dbName == null) { - dbName = this.db.databaseName; - } - - // Create a delete command - var deleteCommand = new DeleteCommand( - this.db - , dbName + "." + this.collectionName - , selector - , flags); - - var self = this; - var errorOptions = shared._getWriteConcern(self, options); - - // Execute the command, do not add a callback as it's async - if(shared._hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - var commandOptions = {}; - // Set safe option - commandOptions['safe'] = true; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // If we have a passed in connection use it - if(options.connection) { - commandOptions.connection = options.connection; - } - - // Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection) - this.db._executeRemoveCommand(deleteCommand, commandOptions, handleWriteResults(function (err, results) { - if(err) return callback(err, null); - if(results == null) return callback(new Error("command failed to return result")); - if(fullResult) return callback(null, results); - callback(null, results[0].n); - })); - } else if(shared._hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - var result = this.db._executeRemoveCommand(deleteCommand); - // If no callback just return - if (!callback) return; - // If error return error - if (result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(); - } -}; - -// *************************************************** -// Save function -// *************************************************** -var save = function save(doc, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - // Throw an error if attempting to perform a bulk operation - if(Array.isArray(doc)) throw new Error("doc parameter must be a single document"); - // Extract the id, if we have one we need to do a update command - var id = doc['_id']; - var commandOptions = shared._getWriteConcern(this, options); - if(options.connection) commandOptions.connection = options.connection; - if(typeof options.fullResult == 'boolean') commandOptions.fullResult = options.fullResult; - - if(id != null) { - commandOptions.upsert = true; - this.update({ _id: id }, doc, commandOptions, callback); - } else { - this.insert(doc, commandOptions, callback && function (err, docs) { - if(err) return callback(err, null); - - if(Array.isArray(docs)) { - callback(err, docs[0]); - } else { - callback(err, docs); - } - }); - } -}; - -// *************************************************** -// Update document function -// *************************************************** -var updateWithWriteCommands = function(self, selector, document, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // Get the intended namespace for the operation - var namespace = self.collectionName; - - // Ensure we have no \x00 bytes in the name causing wrong parsing - if(!!~namespace.indexOf("\x00")) { - return callback(new Error("namespace cannot contain a null character"), null); - } - - // If we are not providing a selector or document throw - if(selector == null || typeof selector != 'object') - return callback(new Error("selector must be a valid JavaScript object")); - if(document == null || typeof document != 'object') - return callback(new Error("document must be a valid JavaScript object")); - - // Check if we have passed in continue on error - var continueOnError = typeof options['keepGoing'] == 'boolean' - ? options['keepGoing'] : false; - continueOnError = typeof options['continueOnError'] == 'boolean' - ? options['continueOnError'] : continueOnError; - - // Do we serialzie functions - var serializeFunctions = typeof options.serializeFunctions != 'boolean' - ? self.serializeFunctions : options.serializeFunctions; - - // Checkout a write connection - var connection = self.db.serverConfig.checkoutWriter(); - if(connection instanceof Error && connection.code == -5000) return callback(connection); - - // Figure out the value of top - var multi = typeof options.multi == 'boolean' ? options.multi : false; - var upsert = typeof options.upsert == 'boolean' ? options.upsert : false; - - // Do we return the actual result document - var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false; - - // Collect errorOptions - var errorOptions = shared._getWriteConcern(self, options); - - // If we have a write command with no callback and w:0 fail - if(errorOptions.w && errorOptions.w != 0 && callback == null) { - throw new Error("writeConcern requires callback") - } - - // Create the write command - var write_command = { - update: namespace, - writeConcern: errorOptions, - ordered: !continueOnError, - updates: [{ - q : selector, - u: document, - multi: multi, - upsert: upsert - }] - } - - // Check if we have a checkKeys override - var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; - - // Execute the write command - self.db.command(write_command - , { connection:connection - , checkKeys: checkKeys - , serializeFunctions: serializeFunctions - , writeCommand: true } - , function(err, result) { - if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null); - if(errorOptions.w == 0) return; - if(callback == null) return; - - if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null); - if(errorOptions.w == 0) return; - if(callback == null) return; - if(err != null) { - return callback(err, null); - } - - // Result has an error - if(!result.ok || Array.isArray(result.writeErrors) && result.writeErrors.length > 0) { - var error = utils.toError(result.writeErrors[0].errmsg); - error.code = result.writeErrors[0].code; - error.err = result.writeErrors[0].errmsg; - error.message = result.writeErrors[0].errmsg; - return callback(error, null); - } - - if(fullResult) return callback(null, result); - // Backward compatibility format - var r = backWardsCompatibiltyResults(result, 'update'); - // Return the results for a whole batch - callback(null, r.n, r) - }); -} - -var backWardsCompatibiltyResults = function(result, op) { - // Upserted - var upsertedValue = null; - var finalResult = null; - var updatedExisting = true; - - // We have a single document upserted result - if(Array.isArray(result.upserted) || result.upserted != null) { - updatedExisting = false; - upsertedValue = result.upserted; - } - - // Final result - if(op == 'remove' || op == 'insert') { - finalResult = {ok: true, n: result.n} - } else { - finalResult = {ok: true, n: result.n, updatedExisting: updatedExisting} - } - - if(upsertedValue != null) finalResult.upserted = upsertedValue; - return finalResult; -} - -var handleWriteResults = function handleWriteResults(callback) { - return function(err, error) { - var documents = error && error.documents; - if(!callback) return; - // We have an error - if(err) return callback(err, null); - // If no document something is terribly wrong - if(error == null) return callback(utils.toError("MongoDB did not return a response")); - // Handle the case where no result was returned - if(error != null && documents == null) { - if(typeof error.err == 'string') { - return callback(utils.toError(error.err)); - } else if(typeof error.errmsg == 'string') { - return callback(utils.toError(error.errmsg)); - } else { - return callback(utils.toError("Unknown MongoDB error")); - } - } - - // Handler normal cases - if(documents[0].err || documents[0].errmsg) { - callback(utils.toError(documents[0])); - } else if(documents[0].jnote || documents[0].wtimeout) { - callback(utils.toError(documents[0])); - } else { - callback(err, documents); - } - } -} - -var update = function update(selector, document, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // Get a connection - var connection = options.connection || this.db.serverConfig.checkoutWriter(); - if(connection instanceof Error && connection.code == -5000) return callback(connection); - var useLegacyOps = options.useLegacyOps == null || options.useLegacyOps == false ? false : true; - // If we support write commands let's perform the insert using it - if(!useLegacyOps && hasWriteCommands(connection) && !Buffer.isBuffer(selector) && !Buffer.isBuffer(document)) { - return updateWithWriteCommands(this, selector, document, options, callback); - } - - // DbName - var dbName = options['dbName']; - // If no dbname defined use the db one - if(dbName == null) { - dbName = this.db.databaseName; - } - - // If we are not providing a selector or document throw - if(selector == null || typeof selector != 'object') return callback(new Error("selector must be a valid JavaScript object")); - if(document == null || typeof document != 'object') return callback(new Error("document must be a valid JavaScript object")); - - // Do we return the actual result document - var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false; - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - options['serializeFunctions'] = options['serializeFunctions']; - } else { - options['serializeFunctions'] = this.serializeFunctions; - } - - // Build the options command - var updateCommand = new UpdateCommand( - this.db - , dbName + "." + this.collectionName - , selector - , document - , options); - - var self = this; - // Unpack the error options if any - var errorOptions = shared._getWriteConcern(this, options); - // If safe is defined check for error message - if(shared._hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - var commandOptions = {}; - // Set safe option - commandOptions['safe'] = errorOptions; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // If we have a passed in connection use it - if(options.connection) { - commandOptions.connection = options.connection; - } - - // Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection) - this.db._executeUpdateCommand(updateCommand, commandOptions, handleWriteResults(function(err, results) { - if(err) return callback(err, null); - if(results == null) return callback(new Error("command failed to return result")); - if(fullResult) return callback(null, results); - callback(null, results[0].n, results[0]); - })); - } else if(shared._hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - // Execute update - var result = this.db._executeUpdateCommand(updateCommand); - // If no callback just return - if (!callback) return; - // If error return error - if (result instanceof Error) { - return callback(result); - } - - // Otherwise just return - return callback(); - } -}; - -// *************************************************** -// findAndModify function -// *************************************************** -var findAndModify = function findAndModify (query, sort, doc, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - var self = this; - - var queryObject = { - 'findandmodify': this.collectionName - , 'query': query - }; - - sort = utils.formattedOrderClause(sort); - if (sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? 1 : 0; - queryObject.remove = options.remove ? 1 : 0; - queryObject.upsert = options.upsert ? 1 : 0; - - if (options.fields) { - queryObject.fields = options.fields; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - // Checkout a write connection - options.connection = self.db.serverConfig.checkoutWriter(); - if(options.connection instanceof Error && options.connection.code == -5000) return callback(options.connection); - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - options['serializeFunctions'] = options['serializeFunctions']; - } else { - options['serializeFunctions'] = this.serializeFunctions; - } - - // No check on the documents - options.checkKeys = false; - - // Execute the command - this.db.command(queryObject - , options, function(err, result) { - if(err) return callback(err, null); - return callback(null, result.value, result); - }); -} - -// *************************************************** -// findAndRemove function -// *************************************************** -var findAndRemove = function(query, sort, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - // Add the remove option - options['remove'] = true; - // Execute the callback - this.findAndModify(query, sort, null, options, callback); -} - -// Map methods -exports.insert = insert; -exports.remove = remove; -exports.save = save; -exports.update = update; -exports.findAndModify = findAndModify; -exports.findAndRemove = findAndRemove; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/geo.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/geo.js deleted file mode 100755 index 05d0c597..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/geo.js +++ /dev/null @@ -1,78 +0,0 @@ -var shared = require('./shared') - , utils = require('../utils'); - -var geoNear = function geoNear(x, y, options, callback) { - var point = typeof(x) == 'object' && x - , args = Array.prototype.slice.call(arguments, point?1:2); - - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - geoNear:this.collectionName, - near: point || [x, y] - } - - // Ensure we have the right read preference inheritance - options.readPreference = shared._getReadConcern(this, options); - - // Exclude readPreference and existing options to prevent user from - // shooting themselves in the foot - var exclude = { - readPreference: true, - geoNear: true, - near: true - }; - - commandObject = utils.decorateCommand(commandObject, options, exclude); - - // Execute the command - this.db.command(commandObject, options, function (err, res) { - if (err) { - callback(err); - } else if (res.err || res.errmsg) { - callback(utils.toError(res)); - } else { - // should we only be returning res.results here? Not sure if the user - // should see the other return information - callback(null, res); - } - }); -} - -var geoHaystackSearch = function geoHaystackSearch(x, y, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - geoSearch:this.collectionName, - near: [x, y] - } - - // Remove read preference from hash if it exists - commandObject = utils.decorateCommand(commandObject, options, {readPreference: true}); - - // Ensure we have the right read preference inheritance - options.readPreference = shared._getReadConcern(this, options); - - // Execute the command - this.db.command(commandObject, options, function (err, res) { - if (err) { - callback(err); - } else if (res.err || res.errmsg) { - callback(utils.toError(res)); - } else { - // should we only be returning res.results here? Not sure if the user - // should see the other return information - callback(null, res); - } - }); -} - -exports.geoNear = geoNear; -exports.geoHaystackSearch = geoHaystackSearch; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/index.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/index.js deleted file mode 100755 index 1b5e1c8d..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/index.js +++ /dev/null @@ -1,98 +0,0 @@ -var utils = require('../utils') - , CommandCursor = require('../command_cursor').CommandCursor; - -var _getWriteConcern = require('./shared')._getWriteConcern; - -var createIndex = function createIndex (fieldOrSpec, options, callback) { - // Clean up call - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - - // Collect errorOptions - var errorOptions = _getWriteConcern(this, options); - // Execute create index - this.db.createIndex(this.collectionName, fieldOrSpec, options, callback); -}; - -var indexExists = function indexExists(indexes, callback) { - this.indexInformation(function(err, indexInformation) { - // If we have an error return - if(err != null) return callback(err, null); - // Let's check for the index names - if(Array.isArray(indexes)) { - for(var i = 0; i < indexes.length; i++) { - if(indexInformation[indexes[i]] == null) { - return callback(null, false); - } - } - - // All keys found return true - return callback(null, true); - } else { - return callback(null, indexInformation[indexes] != null); - } - }); -} - -var dropAllIndexes = function dropIndexes (callback) { - this.db.dropIndex(this.collectionName, '*', function (err, result) { - if(err) return callback(err, false); - callback(null, true); - }); -}; - -var indexInformation = function indexInformation (options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - // Call the index information - this.db.indexInformation(this.collectionName, options, callback); -}; - -var ensureIndex = function ensureIndex (fieldOrSpec, options, callback) { - // Clean up call - if (typeof callback === 'undefined' && typeof options === 'function') { - callback = options; - options = {}; - } - - if (options == null) { - options = {}; - } - - // Execute create index - this.db.ensureIndex(this.collectionName, fieldOrSpec, options, callback); -}; - -var listIndexes = function listIndexes(options) { - options = options || {}; - // Clone the options - options = utils.shallowObjectCopy(options); - - // Checkout the writer - var connection = this.db.serverConfig.checkoutReader(); - - // We have a list collections command - if(connection && connection.serverCapabilities && connection.serverCapabilities.hasListIndexesCommand) { - // Cursor options - var cursor = options.batchSize ? {batchSize: options.batchSize} : {} - // Build the command - var command = { listIndexes: this.collectionName, cursor: cursor }; - // Get the command cursor - return new CommandCursor(this.db, this.db.databaseName + ".$cmd", command); - } - - var collection = this.db.collection('system.indexes'); - return collection.find({ns: this.db.databaseName + "." + this.collectionName}); -}; - -exports.createIndex = createIndex; -exports.indexExists = indexExists; -exports.dropAllIndexes = dropAllIndexes; -exports.indexInformation = indexInformation; -exports.ensureIndex = ensureIndex; -exports.listIndexes = listIndexes; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/query.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/query.js deleted file mode 100755 index 86e8bdd2..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/query.js +++ /dev/null @@ -1,218 +0,0 @@ -var ObjectID = require('bson').ObjectID - , Long = require('bson').Long - , DbCommand = require('../commands/db_command').DbCommand - , CommandCursor = require('../command_cursor').CommandCursor - , Scope = require('../scope').Scope - , shared = require('./shared') - , utils = require('../utils'); - -var testForFields = { - limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1 - , numberOfRetries: 1, awaitdata: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1 - , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1, oplogReplay: 1, connection: 1, maxTimeMS: 1, transforms:1 -}; - -// -// Find method -// -var find = function find () { - var options - , args = Array.prototype.slice.call(arguments, 0) - , has_callback = typeof args[args.length - 1] === 'function' - , has_weird_callback = typeof args[0] === 'function' - , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null) - , len = args.length - , selector = len >= 1 ? args[0] : {} - , fields = len >= 2 ? args[1] : undefined; - - if(len === 1 && has_weird_callback) { - // backwards compat for callback?, options case - selector = {}; - options = args[0]; - } - - if(len === 2 && !Array.isArray(fields)) { - var fieldKeys = Object.keys(fields); - var is_option = false; - - for(var i = 0; i < fieldKeys.length; i++) { - if(testForFields[fieldKeys[i]] != null) { - is_option = true; - break; - } - } - - if(is_option) { - options = fields; - fields = undefined; - } else { - options = {}; - } - } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) { - var newFields = {}; - // Rewrite the array - for(var i = 0; i < fields.length; i++) { - newFields[fields[i]] = 1; - } - // Set the fields - fields = newFields; - } - - if(3 === len) { - options = args[2]; - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - var object = selector; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Validate correctness of the field selector - var object = fields; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Check special case where we are using an objectId - if(selector instanceof ObjectID || (selector != null && selector._bsontype == 'ObjectID')) { - selector = {_id:selector}; - } - - // If it's a serialized fields field we need to just let it through - // user be warned it better be good - if(options && options.fields && !(Buffer.isBuffer(options.fields))) { - fields = {}; - - if(Array.isArray(options.fields)) { - if(!options.fields.length) { - fields['_id'] = 1; - } else { - for (var i = 0, l = options.fields.length; i < l; i++) { - fields[options.fields[i]] = 1; - } - } - } else { - fields = options.fields; - } - } - - if (!options) options = {}; - - var newOptions = {}; - // Make a shallow copy of options - for (var key in options) { - newOptions[key] = options[key]; - } - - newOptions.skip = len > 3 ? args[2] : options.skip ? options.skip : 0; - newOptions.limit = len > 3 ? args[3] : options.limit ? options.limit : 0; - newOptions.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.raw; - newOptions.hint = options.hint != null ? shared.normalizeHintField(options.hint) : this.internalHint; - newOptions.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout; - // If we have overridden slaveOk otherwise use the default db setting - newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.db.slaveOk; - - // Set option - var o = newOptions; - // Support read/readPreference - if(o["read"] != null) o["readPreference"] = o["read"]; - // If no readPreference specified set the collection level readPreference - o.readPreference = o.readPreference ? o.readPreference : this.readPreference; - // If still no readPreference specified set the db level - o.readPreference = o.readPreference ? o.readPreference : this.db.options.readPreference; - // Set slaveok if needed - if(o.readPreference == "secondary" || o.read == "secondaryOnly") o.slaveOk = true; - - // Ensure the query is an object - if(selector != null && typeof selector != 'object') { - throw utils.toError("query selector must be an object"); - } - - // Set the selector - o.selector = selector; - - // Create precursor - var scope = new Scope(this, {}, fields, o); - // Callback for backward compatibility - if(callback) return callback(null, scope.find(selector)); - // Return the pre cursor object - return scope.find(selector); -}; - -var findOne = function findOne () { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - var callback = args.pop(); - var cursor = this.find.apply(this, args).limit(-1).batchSize(1); - - // Return the item - cursor.nextObject(function(err, item) { - if(err != null) return callback(utils.toError(err), null); - callback(null, item); - }); -}; - -var parallelCollectionScan = function parallelCollectionScan (options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {numCursors: 1}; - } - - // Set number of cursors to 1 - options.numCursors = options.numCursors || 1; - options.batchSize = options.batchSize || 1000; - - // Set read preference if we set one - options.readPreference = shared._getReadConcern(this, options); - - // Create command object - var commandObject = { - parallelCollectionScan: this.collectionName - , numCursors: options.numCursors - } - - // Execute the command - this.db.command(commandObject, options, function(err, result) { - if(err) return callback(err, null); - if(result == null) return callback(new Error("no result returned for parallelCollectionScan"), null); - - var cursors = []; - // Create command cursors for each item - for(var i = 0; i < result.cursors.length; i++) { - var rawId = result.cursors[i].cursor.id - // Convert cursorId to Long if needed - var cursorId = typeof rawId == 'number' ? Long.fromNumber(rawId) : rawId; - - // Command cursor options - var commandOptions = { - batchSize: options.batchSize - , cursorId: cursorId - , items: result.cursors[i].cursor.firstBatch - } - - // Add a command cursor - cursors.push(new CommandCursor(self.db, self, {}, commandOptions)); - } - - callback(null, cursors); - }); -} - -exports.find = find; -exports.findOne = findOne; -exports.parallelCollectionScan = parallelCollectionScan; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/shared.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/shared.js deleted file mode 100755 index 77eae039..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/collection/shared.js +++ /dev/null @@ -1,120 +0,0 @@ -// *************************************************** -// Write concerns -// *************************************************** -var _hasWriteConcern = function(errorOptions) { - return errorOptions == true - || errorOptions.w > 0 - || errorOptions.w == 'majority' - || errorOptions.j == true - || errorOptions.journal == true - || errorOptions.fsync == true -} - -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -var _getWriteConcern = function(self, options) { - // Final options - var finalOptions = {w:1}; - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(self.opts.w != null || typeof self.opts.j == 'boolean' || typeof self.opts.journal == 'boolean' || typeof self.opts.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.opts); - } else if(typeof self.opts.safe == "boolean") { - finalOptions = {w: (self.opts.safe ? 1 : 0)}; - } else if(self.db.safe.w != null || typeof self.db.safe.j == 'boolean' || typeof self.db.safe.journal == 'boolean' || typeof self.db.safe.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.safe); - } else if(self.db.options.w != null || typeof self.db.options.j == 'boolean' || typeof self.db.options.journal == 'boolean' || typeof self.db.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.options); - } else if(typeof self.db.safe == "boolean") { - finalOptions = {w: (self.db.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowlegement using w < 1 cannot be combined with journal:true or fsync:true"); - - // Return the options - return finalOptions; -} - -var _getReadConcern = function(self, options) { - if(options.readPreference) return options.readPreference; - if(self.readPreference) return self.readPreference; - if(self.db.readPreference) return self.readPreference; - return 'primary'; -} - -/** - * @ignore - */ -var checkCollectionName = function checkCollectionName (collectionName) { - if('string' !== typeof collectionName) { - throw Error("collection name must be a String"); - } - - if(!collectionName || collectionName.indexOf('..') != -1) { - throw Error("collection names cannot be empty"); - } - - if(collectionName.indexOf('$') != -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { - throw Error("collection names must not contain '$'"); - } - - if(collectionName.match(/^\.|\.$/) != null) { - throw Error("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the colletion name - if(!!~collectionName.indexOf("\x00")) { - throw new Error("collection names cannot contain a null character"); - } -}; - - -/** - * Normalizes a `hint` argument. - * - * @param {String|Object|Array} hint - * @return {Object} - * @api private - */ -var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - - if(typeof hint == 'string') { - finalHint = hint; - } else if(Array.isArray(hint)) { - finalHint = {}; - - hint.forEach(function(param) { - finalHint[param] = 1; - }); - } else if(hint != null && typeof hint == 'object') { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } - - return finalHint; -}; - -exports._getWriteConcern = _getWriteConcern; -exports._hasWriteConcern = _hasWriteConcern; -exports._getReadConcern = _getReadConcern; -exports.checkCollectionName = checkCollectionName; -exports.normalizeHintField = normalizeHintField; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/command_cursor.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/command_cursor.js deleted file mode 100755 index 6d146387..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/command_cursor.js +++ /dev/null @@ -1,384 +0,0 @@ -var Long = require('bson').Long - , Readable = require('stream').Readable || require('readable-stream').Readable - , GetMoreCommand = require('./commands/get_more_command').GetMoreCommand - , inherits = require('util').inherits; - -var CommandCursor = function(db, collection, command, options) { - var self = this; - // Ensure empty options if no options passed - options = options || {}; - - // Set up - Readable.call(this, {objectMode: true}); - - // Default cursor id is 0 - var cursorId = options.cursorId || Long.fromInt(0); - var zeroCursor = Long.fromInt(0); - var state = 'init'; - var batchSize = options.batchSize || 0; - - // Hardcode batch size - if(command && command.cursor) { - batchSize = command.cursor.batchSize || 0; - } - - // BatchSize - var raw = options.raw || false; - var readPreference = options.readPreference || 'primary'; - - // Cursor namespace - this.ns = db.databaseName + "." + collection.collectionName - - // Checkout a connection - var connection = db.serverConfig.checkoutReader(readPreference); - // MaxTimeMS - var maxTimeMS = options.maxTimeMS; - var transform = options.transform; - - // Contains all the items - var items = options.items || null; - - // Execute getmore - var getMore = function(callback) { - // Resolve more of the cursor using the getMore command - var getMoreCommand = new GetMoreCommand(db - , self.ns - , batchSize - , cursorId - ); - - // Set up options - var command_options = { connection:connection }; - - // Execute the getMore Command - db._executeQueryCommand(getMoreCommand, command_options, function(err, result) { - if(err) { - items = []; - state = 'closed'; - return callback(err); - } - - // Return all the documents - callback(null, result); - }); - } - - var exhaustGetMore = function(callback) { - getMore(function(err, result) { - if(err) { - items = []; - state = 'closed'; - return callback(err, null); - } - - // Add the items - items = items.concat(result.documents); - - // Set the cursor id - cursorId = result.cursorId; - if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId); - - // If the cursor is done - if(result.cursorId.equals(zeroCursor)) { - return callback(null, items); - } - - // Check the cursor id - exhaustGetMore(callback); - }); - } - - var exhaustGetMoreEach = function(callback) { - getMore(function(err, result) { - if(err) { - items = []; - state = 'closed'; - return callback(err, null); - } - - // Add the items - items = result.documents; - - // Emit all the items in the first batch - while(items.length > 0) { - callback(null, items.shift()); - } - - // Set the cursor id - cursorId = result.cursorId; - if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId); - - // If the cursor is done - if(result.cursorId.equals(zeroCursor)) { - state = "closed"; - return callback(null, null); - } - - // Check the cursor id - exhaustGetMoreEach(callback); - }); - } - - // - // Get all the elements - // - this.get = function(options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Set the connection to the passed in one if it's provided - connection = options.connection ? options.connection : connection; - - // Command options - var _options = {connection:connection}; - if(typeof maxTimeMS == 'number') _options.maxTimeMS = maxTimeMS; - - // If we have a cursor Id already not equal to 0 we are just going to - // exhaust the cursor - if(cursorId.notEquals(zeroCursor)) { - // If no items set an empty array - items = items || []; - // Exhaust the cursor - return exhaustGetMore(callback); - } - - // Execute the internal command first - db.command(command, _options, function(err, result) { - if(err) { - state = 'closed'; - return callback(err, null); - } - - if(result.cursor && typeof result.cursor.id == 'number') { - // Retrieve the cursor id - cursorId = result.cursor.id; - self.ns = result.cursor.ns; - if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId); - - // Validate cursorId - if(cursorId.equals(zeroCursor)) { - var docs = typeof transform == 'function' ? transform(result.cursor.firstBatch) : result.cursor.firstBatch; - return callback(null, docs); - }; - - // Add to the items - items = result.cursor.firstBatch; - } else { - cursorId = zeroCursor; - var docs = typeof transform == 'function' ? transform(items) : items; - items = []; - return callback(null, items); - } - - // Execute the getMore - exhaustGetMore(callback); - }); - } - - this.toArray = this.get; - - // - // Iterate over all the items - // - this.each = function(options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // If it's a closed cursor return error - if(this.isClosed()) return callback(new Error("cursor is closed")); - // Set the connection to the passed in one if it's provided - connection = options.connection ? options.connection : connection; - - // Command options - var _options = {connection:connection}; - if(typeof maxTimeMS == 'number') _options.maxTimeMS = maxTimeMS; - - // If we have a cursor Id already not equal to 0 we are just going to - // exhaust the cursor - if(cursorId.notEquals(zeroCursor)) { - // If no items set an empty array - items = items || []; - - // Emit all the items in the first batch - while(items.length > 0) { - callback(null, items.shift()); - } - - // Exhaust the cursor - return exhaustGetMoreEach(callback); - } - - // Execute the internal command first - db.command(command, _options, function(err, result) { - if(err) { - state = 'closed'; - return callback(err, null); - } - - // Get all the items - items = result.cursor.firstBatch; - - // Emit all the items in the first batch - while(items.length > 0) { - callback(null, items.shift()); - } - - // Retrieve the cursor id - cursorId = result.cursor.id; - self.ns = result.cursor.ns; - if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId); - - // If no cursor we just finish up the current batch of items - if(cursorId.equals(zeroCursor)) { - state = 'closed'; - return callback(null, null); - } - - // Emit each until no more getMore's - exhaustGetMoreEach(callback); - }); - } - - // - // Get the next object - // - this.next = function(options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // If it's a closed cursor return error - if(this.isClosed()) return callback(new Error("cursor is closed")); - - // Set the connection to the passed in one if it's provided - connection = options.connection ? options.connection : connection; - - // Command options - var _options = {connection:connection}; - if(typeof maxTimeMS == 'number') _options.maxTimeMS = maxTimeMS; - - // If we have a cursor Id already not equal to 0 we are just going to - // going to bypass the command execution - if(cursorId.notEquals(zeroCursor)) { - items = items || []; - } - - // Execute the internal command first - if(!items) { - db.command(command, _options, function(err, result) { - if(err) { - state = 'closed'; - return callback(err, null); - } - - // Retrieve the cursor id - cursorId = result.cursor.id; - self.ns = result.cursor.ns; - if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId); - // Get the first batch results - items = result.cursor.firstBatch; - // We have items return the first one - if(items.length > 0) { - callback(null, items.shift()); - } else { - state = 'closed'; - callback(null, null); - } - }); - } else if(items.length > 0) { - callback(null, items.shift()); - } else if(items.length == 0 && cursorId.equals(zeroCursor)) { - state = 'closed'; - callback(null, null); - } else { - // Execute a getMore - getMore(function(err, result) { - if(err) { - state = 'closed'; - return callback(err, null); - } - - // Set the cursor id - cursorId = result.cursorId; - if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId); - - // Add the items - items = items.concat(result.documents); - // If no more items - if(items.length == 0) { - state = 'closed'; - return callback(null, null); - } - - // Return the item - return callback(null, items.shift()); - }) - } - } - - // Validate if the cursor is closed - this.isClosed = function() { - return state == 'closed'; - } - - // Allow us to set the MaxTimeMS - this.maxTimeMS = function(_maxTimeMS) { - maxTimeMS = _maxTimeMS; - } - - // Close the cursor sending a kill cursor command if needed - this.close = function(callback) { - // Close the cursor if not needed - if(cursorId instanceof Long && cursorId.greaterThan(Long.fromInt(0))) { - try { - var command = new KillCursorCommand(this.db, [cursorId]); - // Added an empty callback to ensure we don't throw any null exceptions - db._executeQueryCommand(command, {connection:connection}); - } catch(err) {} - } - - // Null out the connection - connection = null; - // Reset cursor id - cursorId = Long.fromInt(0); - // Set to closed status - state = 'closed'; - // Clear out all the items - items = null; - - if(callback) { - callback(null, null); - } - } - - // - // Stream method - // - this._read = function(n) { - var self = this; - // Read the next command cursor doc - self.next(function(err, result) { - if(err) { - self.emit('error', err); - return self.push(null); - } - - self.push(result); - }); - } -} - -// Inherit from Readable -if(Readable != null) { - inherits(CommandCursor, Readable); -} - -exports.CommandCursor = CommandCursor; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/base_command.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/base_command.js deleted file mode 100755 index 95585828..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/base_command.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - Base object used for common functionality -**/ -var BaseCommand = exports.BaseCommand = function BaseCommand() { -}; - -var id = 1; -BaseCommand.prototype.getRequestId = function getRequestId() { - if (!this.requestId) this.requestId = id++; - return this.requestId; -}; - -BaseCommand.prototype.setMongosReadPreference = function setMongosReadPreference(readPreference, tags) {} - -BaseCommand.prototype.updateRequestId = function() { - this.requestId = id++; - return this.requestId; -}; - -// OpCodes -BaseCommand.OP_REPLY = 1; -BaseCommand.OP_MSG = 1000; -BaseCommand.OP_UPDATE = 2001; -BaseCommand.OP_INSERT = 2002; -BaseCommand.OP_GET_BY_OID = 2003; -BaseCommand.OP_QUERY = 2004; -BaseCommand.OP_GET_MORE = 2005; -BaseCommand.OP_DELETE = 2006; -BaseCommand.OP_KILL_CURSORS = 2007; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/db_command.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/db_command.js deleted file mode 100755 index 39bdb6e2..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/db_command.js +++ /dev/null @@ -1,101 +0,0 @@ -var QueryCommand = require('./query_command').QueryCommand, - InsertCommand = require('./insert_command').InsertCommand, - inherits = require('util').inherits, - utils = require('../utils'), - crypto = require('crypto'); - -/** - Db Command -**/ -var DbCommand = exports.DbCommand = function(dbInstance, collectionName, queryOptions, numberToSkip, numberToReturn, query, returnFieldSelector, options) { - QueryCommand.call(this); - this.collectionName = collectionName; - this.queryOptions = queryOptions; - this.numberToSkip = numberToSkip; - this.numberToReturn = numberToReturn; - this.query = query; - this.returnFieldSelector = returnFieldSelector; - this.db = dbInstance; - - // Set the slave ok bit - if(this.db && this.db.slaveOk) { - this.queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Make sure we don't get a null exception - options = options == null ? {} : options; - - // Allow for overriding the BSON checkKeys function - this.checkKeys = typeof options['checkKeys'] == 'boolean' ? options["checkKeys"] : true; - - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(DbCommand, QueryCommand); - -// Constants -DbCommand.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; -DbCommand.SYSTEM_INDEX_COLLECTION = "system.indexes"; -DbCommand.SYSTEM_PROFILE_COLLECTION = "system.profile"; -DbCommand.SYSTEM_USER_COLLECTION = "system.users"; -DbCommand.SYSTEM_COMMAND_COLLECTION = "$cmd"; -DbCommand.SYSTEM_JS_COLLECTION = "system.js"; - -// New commands -DbCommand.NcreateIsMasterCommand = function(db, databaseName) { - return new DbCommand(db, databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'ismaster':1}, null); -}; - -// Provide constructors for different db commands -DbCommand.createIsMasterCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'ismaster':1}, null); -}; - -DbCommand.createGetLastErrorCommand = function(options, db) { - if (typeof db === 'undefined') { - db = options; - options = {}; - } - // Final command - var command = {'getlasterror':1}; - // If we have an options Object let's merge in the fields (fsync/wtimeout/w) - if('object' === typeof options) { - for(var name in options) { - command[name] = options[name] - } - } - - // Special case for w == 1, remove the w - if(1 == command.w) { - delete command.w; - } - - // Execute command - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command, null); -}; - -DbCommand.createGetLastStatusCommand = DbCommand.createGetLastErrorCommand; - -DbCommand.createDbCommand = function(db, command_hash, options, auth_db) { - var db_name = (auth_db ? auth_db : db.databaseName) + "." + DbCommand.SYSTEM_COMMAND_COLLECTION; - options = options == null ? {checkKeys: false} : options; - return new DbCommand(db, db_name, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null, options); -}; - -DbCommand.createAdminDbCommand = function(db, command_hash) { - return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null); -}; - -DbCommand.createAdminDbCommandSlaveOk = function(db, command_hash) { - return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT | QueryCommand.OPTS_SLAVE, 0, -1, command_hash, null); -}; - -DbCommand.createDbSlaveOkCommand = function(db, command_hash, options) { - options = options == null ? {checkKeys: false} : options; - var dbName = options.dbName ? options.dbName : db.databaseName; - var flags = options.slaveOk ? QueryCommand.OPTS_NO_CURSOR_TIMEOUT | QueryCommand.OPTS_SLAVE : QueryCommand.OPTS_NO_CURSOR_TIMEOUT; - return new DbCommand(db, dbName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, flags, 0, -1, command_hash, null, options); -}; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/delete_command.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/delete_command.js deleted file mode 100755 index 61a37edf..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/delete_command.js +++ /dev/null @@ -1,129 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Insert Document Command -**/ -var DeleteCommand = exports.DeleteCommand = function(db, collectionName, selector, flags) { - BaseCommand.call(this); - - // Validate correctness off the selector - var object = selector; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("delete raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - this.flags = flags; - this.collectionName = collectionName; - this.selector = selector; - this.db = db; -}; - -inherits(DeleteCommand, BaseCommand); - -DeleteCommand.OP_DELETE = 2006; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - cstring fullCollectionName; // "dbname.collectionname" - int32 ZERO; // 0 - reserved for future use - mongo.BSON selector; // query object. See below for details. -} -*/ -DeleteCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + this.db.bson.calculateObjectSize(this.selector, false, true) + (4 * 4); - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (DeleteCommand.OP_DELETE >> 24) & 0xff; - _command[_index + 2] = (DeleteCommand.OP_DELETE >> 16) & 0xff; - _command[_index + 1] = (DeleteCommand.OP_DELETE >> 8) & 0xff; - _command[_index] = DeleteCommand.OP_DELETE & 0xff; - // Adjust index - _index = _index + 4; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write the flags - _command[_index + 3] = (this.flags >> 24) & 0xff; - _command[_index + 2] = (this.flags >> 16) & 0xff; - _command[_index + 1] = (this.flags >> 8) & 0xff; - _command[_index] = this.flags & 0xff; - // Adjust index - _index = _index + 4; - - // Document binary length - var documentLength = 0 - - // Serialize the selector - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(this.selector)) { - documentLength = this.selector.length; - // Copy the data into the current buffer - this.selector.copy(_command, _index); - } else { - documentLength = this.db.bson.serializeWithBufferAndIndex(this.selector, false, _command, _index) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - return _command; -}; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/get_more_command.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/get_more_command.js deleted file mode 100755 index 1b6b1727..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/get_more_command.js +++ /dev/null @@ -1,88 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits, - binaryutils = require('../utils'); - -/** - Get More Document Command -**/ -var GetMoreCommand = exports.GetMoreCommand = function(db, collectionName, numberToReturn, cursorId) { - BaseCommand.call(this); - - this.collectionName = collectionName; - this.numberToReturn = numberToReturn; - this.cursorId = cursorId; - this.db = db; -}; - -inherits(GetMoreCommand, BaseCommand); - -GetMoreCommand.OP_GET_MORE = 2005; - -GetMoreCommand.prototype.toBinary = function() { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 8 + (4 * 4); - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index++] = totalLengthOfCommand & 0xff; - _command[_index++] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index++] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index++] = (totalLengthOfCommand >> 24) & 0xff; - - // Write the request ID - _command[_index++] = this.requestId & 0xff; - _command[_index++] = (this.requestId >> 8) & 0xff; - _command[_index++] = (this.requestId >> 16) & 0xff; - _command[_index++] = (this.requestId >> 24) & 0xff; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the op_code for the command - _command[_index++] = GetMoreCommand.OP_GET_MORE & 0xff; - _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 8) & 0xff; - _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 16) & 0xff; - _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 24) & 0xff; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Number of documents to return - _command[_index++] = this.numberToReturn & 0xff; - _command[_index++] = (this.numberToReturn >> 8) & 0xff; - _command[_index++] = (this.numberToReturn >> 16) & 0xff; - _command[_index++] = (this.numberToReturn >> 24) & 0xff; - - // Encode the cursor id - var low_bits = this.cursorId.getLowBits(); - // Encode low bits - _command[_index++] = low_bits & 0xff; - _command[_index++] = (low_bits >> 8) & 0xff; - _command[_index++] = (low_bits >> 16) & 0xff; - _command[_index++] = (low_bits >> 24) & 0xff; - - var high_bits = this.cursorId.getHighBits(); - // Encode high bits - _command[_index++] = high_bits & 0xff; - _command[_index++] = (high_bits >> 8) & 0xff; - _command[_index++] = (high_bits >> 16) & 0xff; - _command[_index++] = (high_bits >> 24) & 0xff; - // Return command - return _command; -}; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/insert_command.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/insert_command.js deleted file mode 100755 index c6e51e95..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/insert_command.js +++ /dev/null @@ -1,161 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Insert Document Command -**/ -var InsertCommand = exports.InsertCommand = function(db, collectionName, checkKeys, options) { - BaseCommand.call(this); - - this.collectionName = collectionName; - this.documents = []; - this.checkKeys = checkKeys == null ? true : checkKeys; - this.db = db; - this.flags = 0; - this.serializeFunctions = false; - - // Ensure valid options hash - options = options == null ? {} : options; - - // Check if we have keepGoing set -> set flag if it's the case - if(options['keepGoing'] != null && options['keepGoing']) { - // This will finish inserting all non-index violating documents even if it returns an error - this.flags = 1; - } - - // Check if we have keepGoing set -> set flag if it's the case - if(options['continueOnError'] != null && options['continueOnError']) { - // This will finish inserting all non-index violating documents even if it returns an error - this.flags = 1; - } - - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(InsertCommand, BaseCommand); - -// OpCodes -InsertCommand.OP_INSERT = 2002; - -InsertCommand.prototype.add = function(document) { - if(Buffer.isBuffer(document)) { - var object_size = document[0] | document[1] << 8 | document[2] << 16 | document[3] << 24; - if(object_size != document.length) { - var error = new Error("insert raw message size does not match message header size [" + document.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - this.documents.push(document); - return this; -}; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - cstring fullCollectionName; // "dbname.collectionname" - BSON[] documents; // one or more documents to insert into the collection -} -*/ -InsertCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + (4 * 4); - // var docLength = 0 - for(var i = 0; i < this.documents.length; i++) { - if(Buffer.isBuffer(this.documents[i])) { - totalLengthOfCommand += this.documents[i].length; - } else { - // Calculate size of document - totalLengthOfCommand += this.db.bson.calculateObjectSize(this.documents[i], this.serializeFunctions, true); - } - } - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (InsertCommand.OP_INSERT >> 24) & 0xff; - _command[_index + 2] = (InsertCommand.OP_INSERT >> 16) & 0xff; - _command[_index + 1] = (InsertCommand.OP_INSERT >> 8) & 0xff; - _command[_index] = InsertCommand.OP_INSERT & 0xff; - // Adjust index - _index = _index + 4; - // Write flags if any - _command[_index + 3] = (this.flags >> 24) & 0xff; - _command[_index + 2] = (this.flags >> 16) & 0xff; - _command[_index + 1] = (this.flags >> 8) & 0xff; - _command[_index] = this.flags & 0xff; - // Adjust index - _index = _index + 4; - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write all the bson documents to the buffer at the index offset - for(var i = 0; i < this.documents.length; i++) { - // Document binary length - var documentLength = 0 - var object = this.documents[i]; - - // Serialize the selector - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(object)) { - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - // Serialize the document straight to the buffer - documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - } - - return _command; -}; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js deleted file mode 100755 index d8ccb0c3..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js +++ /dev/null @@ -1,98 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits, - binaryutils = require('../utils'); - -/** - Insert Document Command -**/ -var KillCursorCommand = exports.KillCursorCommand = function(db, cursorIds) { - BaseCommand.call(this); - - this.cursorIds = cursorIds; - this.db = db; -}; - -inherits(KillCursorCommand, BaseCommand); - -KillCursorCommand.OP_KILL_CURSORS = 2007; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - int32 numberOfCursorIDs; // number of cursorIDs in message - int64[] cursorIDs; // array of cursorIDs to close -} -*/ -KillCursorCommand.prototype.toBinary = function() { - // Calculate total length of the document - var totalLengthOfCommand = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (KillCursorCommand.OP_KILL_CURSORS >> 24) & 0xff; - _command[_index + 2] = (KillCursorCommand.OP_KILL_CURSORS >> 16) & 0xff; - _command[_index + 1] = (KillCursorCommand.OP_KILL_CURSORS >> 8) & 0xff; - _command[_index] = KillCursorCommand.OP_KILL_CURSORS & 0xff; - // Adjust index - _index = _index + 4; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Number of cursors to kill - var numberOfCursors = this.cursorIds.length; - _command[_index + 3] = (numberOfCursors >> 24) & 0xff; - _command[_index + 2] = (numberOfCursors >> 16) & 0xff; - _command[_index + 1] = (numberOfCursors >> 8) & 0xff; - _command[_index] = numberOfCursors & 0xff; - // Adjust index - _index = _index + 4; - - // Encode all the cursors - for(var i = 0; i < this.cursorIds.length; i++) { - // Encode the cursor id - var low_bits = this.cursorIds[i].getLowBits(); - // Encode low bits - _command[_index + 3] = (low_bits >> 24) & 0xff; - _command[_index + 2] = (low_bits >> 16) & 0xff; - _command[_index + 1] = (low_bits >> 8) & 0xff; - _command[_index] = low_bits & 0xff; - // Adjust index - _index = _index + 4; - - var high_bits = this.cursorIds[i].getHighBits(); - // Encode high bits - _command[_index + 3] = (high_bits >> 24) & 0xff; - _command[_index + 2] = (high_bits >> 16) & 0xff; - _command[_index + 1] = (high_bits >> 8) & 0xff; - _command[_index] = high_bits & 0xff; - // Adjust index - _index = _index + 4; - } - - return _command; -}; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/query_command.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/query_command.js deleted file mode 100755 index 196c9f17..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/query_command.js +++ /dev/null @@ -1,296 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Insert Document Command -**/ -var QueryCommand = exports.QueryCommand = function(db, collectionName, queryOptions, numberToSkip, numberToReturn, query, returnFieldSelector, options) { - BaseCommand.call(this); - - // Validate correctness off the selector - var object = query, - object_size; - if(Buffer.isBuffer(object)) { - object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - object = returnFieldSelector; - if(Buffer.isBuffer(object)) { - object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Make sure we don't get a null exception - options = options == null ? {} : options; - // Set up options - this.collectionName = collectionName; - this.queryOptions = queryOptions; - this.numberToSkip = numberToSkip; - this.numberToReturn = numberToReturn; - - // Ensure we have no null query - query = query == null ? {} : query; - // Wrap query in the $query parameter so we can add read preferences for mongos - this.query = query; - this.returnFieldSelector = returnFieldSelector; - this.db = db; - - // Force the slave ok flag to be set if we are not using primary read preference - if(this.db && this.db.slaveOk) { - this.queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // If checkKeys set - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; - - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(QueryCommand, BaseCommand); - -QueryCommand.OP_QUERY = 2004; - -/* - * Adds the read prefrence to the current command - */ -QueryCommand.prototype.setMongosReadPreference = function(readPreference, tags) { - // No read preference specified - if(readPreference == false) return; - // If we have readPreference set to true set to secondary prefered - if(readPreference == true) { - readPreference = 'secondaryPreferred'; - } else if(readPreference == 'false') { - readPreference = 'primary'; - } - - // If we have primary read preference ignore it - if(readPreference == 'primary' - || readPreference.mode == 'primary') return; - - // Force the slave ok flag to be set if we are not using primary read preference - if(readPreference != false && readPreference != 'primary') { - this.queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Backward compatibility, ensure $query only set on read preference so 1.8.X works - if((readPreference != null || tags != null) && this.query['$query'] == null) { - this.query = {'$query': this.query}; - } - - // If we have no readPreference set and no tags, check if the slaveOk bit is set - if(readPreference == null && tags == null) { - // If we have a slaveOk bit set the read preference for MongoS - if(this.queryOptions & QueryCommand.OPTS_SLAVE) { - this.query['$readPreference'] = {mode: 'secondary'} - } else { - this.query['$readPreference'] = {mode: 'primary'} - } - } - - // Build read preference object - if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') { - this.query['$readPreference'] = readPreference.toObject(); - } else if(readPreference != null) { - // Add the read preference - this.query['$readPreference'] = {mode: readPreference}; - - // If we have tags let's add them - if(tags != null) { - this.query['$readPreference']['tags'] = tags; - } - } -} - -/* -struct { - MsgHeader header; // standard message header - int32 opts; // query options. See below for details. - cstring fullCollectionName; // "dbname.collectionname" - int32 numberToSkip; // number of documents to skip when returning results - int32 numberToReturn; // number of documents to return in the first OP_REPLY - BSON query ; // query object. See below for details. - [ BSON returnFieldSelector; ] // OPTIONAL : selector indicating the fields to return. See below for details. -} -*/ -QueryCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Total length of the command - var totalLengthOfCommand = 0; - // Calculate total length of the document - if(Buffer.isBuffer(this.query)) { - totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 4 + this.query.length + (4 * 4); - } else { - totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 4 + this.db.bson.calculateObjectSize(this.query, this.serializeFunctions, true) + (4 * 4); - } - - // Calculate extra fields size - if(this.returnFieldSelector != null && !(Buffer.isBuffer(this.returnFieldSelector))) { - if(Object.keys(this.returnFieldSelector).length > 0) { - totalLengthOfCommand += this.db.bson.calculateObjectSize(this.returnFieldSelector, this.serializeFunctions, true); - } - } else if(Buffer.isBuffer(this.returnFieldSelector)) { - totalLengthOfCommand += this.returnFieldSelector.length; - } - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (QueryCommand.OP_QUERY >> 24) & 0xff; - _command[_index + 2] = (QueryCommand.OP_QUERY >> 16) & 0xff; - _command[_index + 1] = (QueryCommand.OP_QUERY >> 8) & 0xff; - _command[_index] = QueryCommand.OP_QUERY & 0xff; - // Adjust index - _index = _index + 4; - - // Write the query options - _command[_index + 3] = (this.queryOptions >> 24) & 0xff; - _command[_index + 2] = (this.queryOptions >> 16) & 0xff; - _command[_index + 1] = (this.queryOptions >> 8) & 0xff; - _command[_index] = this.queryOptions & 0xff; - // Adjust index - _index = _index + 4; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write the number of documents to skip - _command[_index + 3] = (this.numberToSkip >> 24) & 0xff; - _command[_index + 2] = (this.numberToSkip >> 16) & 0xff; - _command[_index + 1] = (this.numberToSkip >> 8) & 0xff; - _command[_index] = this.numberToSkip & 0xff; - // Adjust index - _index = _index + 4; - - // Write the number of documents to return - _command[_index + 3] = (this.numberToReturn >> 24) & 0xff; - _command[_index + 2] = (this.numberToReturn >> 16) & 0xff; - _command[_index + 1] = (this.numberToReturn >> 8) & 0xff; - _command[_index] = this.numberToReturn & 0xff; - // Adjust index - _index = _index + 4; - - // Document binary length - var documentLength = 0 - var object = this.query; - - // Serialize the selector - if(Buffer.isBuffer(object)) { - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - // If $query we need to check for a valid document - if(this.query['$query']) { - this.db.bson.serializeWithBufferAndIndex(object['$query'], this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - // Cannot check keys due to $query - this.checkKeys = false; - } - - // Serialize the document straight to the buffer - documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // // Add terminating 0 for the object - _command[_index - 1] = 0; - - // Push field selector if available - if(this.returnFieldSelector != null && !(Buffer.isBuffer(this.returnFieldSelector))) { - if(Object.keys(this.returnFieldSelector).length > 0) { - var documentLength = this.db.bson.serializeWithBufferAndIndex(this.returnFieldSelector, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - } - } if(this.returnFieldSelector != null && Buffer.isBuffer(this.returnFieldSelector)) { - // Document binary length - var documentLength = 0 - var object = this.returnFieldSelector; - - // Serialize the selector - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - } - - // Return finished command - return _command; -}; - -// Constants -QueryCommand.OPTS_NONE = 0; -QueryCommand.OPTS_TAILABLE_CURSOR = 2; -QueryCommand.OPTS_SLAVE = 4; -QueryCommand.OPTS_OPLOG_REPLAY = 8; -QueryCommand.OPTS_NO_CURSOR_TIMEOUT = 16; -QueryCommand.OPTS_AWAIT_DATA = 32; -QueryCommand.OPTS_EXHAUST = 64; -QueryCommand.OPTS_PARTIAL = 128; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/update_command.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/update_command.js deleted file mode 100755 index daa3cba4..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/commands/update_command.js +++ /dev/null @@ -1,189 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Update Document Command -**/ -var UpdateCommand = exports.UpdateCommand = function(db, collectionName, spec, document, options) { - BaseCommand.call(this); - - var object = spec; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("update spec raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - var object = document; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("update document raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - this.collectionName = collectionName; - this.spec = spec; - this.document = document; - this.db = db; - this.serializeFunctions = false; - this.checkKeys = typeof options.checkKeys != 'boolean' ? false : options.checkKeys; - - // Generate correct flags - var db_upsert = 0; - var db_multi_update = 0; - db_upsert = options != null && options['upsert'] != null ? (options['upsert'] == true ? 1 : 0) : db_upsert; - db_multi_update = options != null && options['multi'] != null ? (options['multi'] == true ? 1 : 0) : db_multi_update; - - // Flags - this.flags = parseInt(db_multi_update.toString() + db_upsert.toString(), 2); - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(UpdateCommand, BaseCommand); - -UpdateCommand.OP_UPDATE = 2001; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - cstring fullCollectionName; // "dbname.collectionname" - int32 flags; // bit vector. see below - BSON spec; // the query to select the document - BSON document; // the document data to update with or insert -} -*/ -UpdateCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + this.db.bson.calculateObjectSize(this.spec, false, true) + - this.db.bson.calculateObjectSize(this.document, this.serializeFunctions, true) + (4 * 4); - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (UpdateCommand.OP_UPDATE >> 24) & 0xff; - _command[_index + 2] = (UpdateCommand.OP_UPDATE >> 16) & 0xff; - _command[_index + 1] = (UpdateCommand.OP_UPDATE >> 8) & 0xff; - _command[_index] = UpdateCommand.OP_UPDATE & 0xff; - // Adjust index - _index = _index + 4; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write the update flags - _command[_index + 3] = (this.flags >> 24) & 0xff; - _command[_index + 2] = (this.flags >> 16) & 0xff; - _command[_index + 1] = (this.flags >> 8) & 0xff; - _command[_index] = this.flags & 0xff; - // Adjust index - _index = _index + 4; - - // Document binary length - var documentLength = 0 - var object = this.spec; - - // Serialize the selector - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) throw new Error("raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, false) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - - // Document binary length - var documentLength = 0 - var object = this.document; - - // Serialize the document - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) throw new Error("raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - documentLength = this.db.bson.serializeWithBufferAndIndex(object, false, _command, _index, this.serializeFunctions) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - - return _command; -}; - -// Constants -UpdateCommand.DB_UPSERT = 0; -UpdateCommand.DB_MULTI_UPDATE = 1; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/base.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/base.js deleted file mode 100755 index b8c13436..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/base.js +++ /dev/null @@ -1,515 +0,0 @@ -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , utils = require('../utils') - , mongodb_cr_authenticate = require('../auth/mongodb_cr.js').authenticate - , mongodb_gssapi_authenticate = require('../auth/mongodb_gssapi.js').authenticate - , mongodb_sspi_authenticate = require('../auth/mongodb_sspi.js').authenticate - , mongodb_plain_authenticate = require('../auth/mongodb_plain.js').authenticate - , mongodb_x509_authenticate = require('../auth/mongodb_x509.js').authenticate - , mongodb_scram_authenticate = require('../auth/mongodb_scram.js').authenticate; - -var id = 0; - -/** - * Internal class for callback storage - * @ignore - */ -var CallbackStore = function() { - // Make class an event emitter - EventEmitter.call(this); - // Add a info about call variable - this._notReplied = {}; - this.id = id++; -} - -/** - * @ignore - */ -inherits(CallbackStore, EventEmitter); - -CallbackStore.prototype.notRepliedToIds = function() { - return Object.keys(this._notReplied); -} - -CallbackStore.prototype.callbackInfo = function(id) { - return this._notReplied[id]; -} - -/** - * Internal class for holding non-executed commands - * @ignore - */ -var NonExecutedOperationStore = function(config) { - var commands = { - read: [] - , write_reads: [] - , write: [] - }; - - // Execute all callbacks - var fireCallbacksWithError = function(error, commands) { - while(commands.length > 0) { - var command = commands.shift(); - if(typeof command.callback == 'function') { - command.callback(error); - } - } - } - - this.count = function() { - return commands.read.length - + commands.write_reads.length - + commands.write.length; - } - - this.write = function(op) { - commands.write.push(op); - } - - this.read_from_writer = function(op) { - commands.write_reads.push(op); - } - - this.read = function(op) { - commands.read.push(op); - } - - this.validateBufferLimit = function(numberToFailOn) { - if(numberToFailOn == -1 || numberToFailOn == null) - return true; - - // Error passed back - var error = utils.toError("No connection operations buffering limit of " + numberToFailOn + " reached"); - - // If we have passed the number of items to buffer we need to fail - if(numberToFailOn < this.count()) { - // Fail all of the callbacks - fireCallbacksWithError(error, commands.read); - fireCallbacksWithError(error, commands.write_reads); - fireCallbacksWithError(error, commands.write); - - // Report back that the buffer has been filled - return false; - } - - // There is still some room to go - return true; - } - - this.execute_queries = function(executeInsertCommand) { - var connection = config.checkoutReader(); - if(connection == null || connection instanceof Error) return; - - // Write out all the queries - while(commands.read.length > 0) { - // Get the next command - var command = commands.read.shift(); - command.options.connection = connection; - // Execute the next command - command.executeQueryCommand(command.db, command.db_command, command.options, command.callback); - } - } - - this.execute_writes = function() { - var connection = config.checkoutWriter(); - if(connection == null || connection instanceof Error) return; - - // Write out all the queries to the primary - while(commands.write_reads.length > 0) { - // Get the next command - var command = commands.write_reads.shift(); - command.options.connection = connection; - // Execute the next command - command.executeQueryCommand(command.db, command.db_command, command.options, command.callback); - } - - // Execute all write operations - while(commands.write.length > 0) { - // Get the next command - var command = commands.write.shift(); - // Set the connection - command.options.connection = connection; - // Execute the next command - command.executeInsertCommand(command.db, command.db_command, command.options, command.callback); - } - } -} - -/** - * Internal class for authentication storage - * @ignore - */ -var AuthStore = function() { - var _auths = []; - - this.add = function(authMechanism, dbName, username, password, authdbName, gssapiServiceName) { - // Check for duplicates - if(!this.contains(dbName)) { - // Base config - var config = { - 'username':username - , 'password':password - , 'db': dbName - , 'authMechanism': authMechanism - , 'gssapiServiceName': gssapiServiceName - }; - - // Add auth source if passed in - if(typeof authdbName == 'string') { - config['authdb'] = authdbName; - } - - // Push the config - _auths.push(config); - } - } - - this.contains = function(dbName) { - for(var i = 0; i < _auths.length; i++) { - if(_auths[i].db == dbName) return true; - } - - return false; - } - - this.remove = function(dbName) { - var newAuths = []; - - // Filter out all the login details - for(var i = 0; i < _auths.length; i++) { - if(_auths[i].db != dbName) newAuths.push(_auths[i]); - } - - // Set the filtered list - _auths = newAuths; - } - - this.get = function(index) { - return _auths[index]; - } - - this.length = function() { - return _auths.length; - } - - this.toArray = function() { - return _auths.slice(0); - } -} - -/** - * Internal class for storing db references - * @ignore - */ -var DbStore = function() { - var _dbs = []; - - this.add = function(db) { - var found = false; - - // Only add if it does not exist already - for(var i = 0; i < _dbs.length; i++) { - if(db.databaseName == _dbs[i].databaseName) found = true; - } - - // Only add if it does not already exist - if(!found) { - _dbs.push(db); - } - } - - this.reset = function() { - _dbs = []; - } - - this.db = function() { - return _dbs; - } - - this.fetch = function(databaseName) { - // Only add if it does not exist already - for(var i = 0; i < _dbs.length; i++) { - if(databaseName == _dbs[i].databaseName) - return _dbs[i]; - } - - return null; - } - - this.emit = function(event, message, object, reset, filterDb, rethrow_if_no_listeners) { - var emitted = false; - - // Not emitted and we have enabled rethrow, let process.uncaughtException - // deal with the issue - if(!emitted && rethrow_if_no_listeners) { - return process.nextTick(function() { - throw message; - }) - } - - // Emit the events - for(var i = 0; i < _dbs.length; i++) { - if(_dbs[i].listeners(event).length > 0) { - if(filterDb == null || filterDb.databaseName !== _dbs[i].databaseName - || filterDb.tag !== _dbs[i].tag) { - _dbs[i].emit(event, message, object == null ? _dbs[i] : object); - emitted = true; - } - } - } - - // Emit error message - if(message - && event == 'error' - && !emitted - && rethrow_if_no_listeners - && object && object.db) { - process.nextTick(function() { - object.db.emit(event, message, null); - }) - } - } -} - -var Base = function Base() { - EventEmitter.call(this); - - // Callback store is part of connection specification - if(Base._callBackStore == null) { - Base._callBackStore = new CallbackStore(); - } - - // Create a new auth store - var auth = new AuthStore(); - - Object.defineProperty(this, "auth", {enumerable: true - , get: function() { return auth; } - }); - - // Create a new callback store - this._callBackStore = new CallbackStore(); - // All commands not being executed - this._commandsStore = new NonExecutedOperationStore(this); - // Contains all the dbs attached to this server config - this._dbStore = new DbStore(); -} - -/** - * @ignore - */ -inherits(Base, EventEmitter); - -/** - * @ignore - */ -Base.prototype._apply_auths = function(db, callback) { - _apply_auths_serially(this, db, this.auth.toArray(), callback); -} - -var _apply_auths_serially = function(self, db, auths, callback) { - if(auths.length == 0) return callback(null, null); - // Get the first auth - var auth = auths.shift(); - var connections = self.allRawConnections(); - var connectionsLeft = connections.length; - var options = {}; - - if(auth.authMechanism == 'GSSAPI') { - // We have the kerberos library, execute auth process - if(process.platform == 'win32') { - mongodb_sspi_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } else { - mongodb_gssapi_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } - } else if(auth.authMechanism == 'MONGODB-CR') { - mongodb_cr_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } else if(auth.authMechanism == 'SCRAM-SHA-1') { - mongodb_scram_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } else if(auth.authMechanism == 'PLAIN') { - mongodb_plain_authenticate(db, auth.username, auth.password, options, callback); - } else if(auth.authMechanism == 'MONGODB-X509') { - mongodb_x509_authenticate(db, auth.username, auth.password, options, callback); - } -} - -/** - * Fire all the errors - * @ignore - */ -Base.prototype.__executeAllCallbacksWithError = function(err) { - // Check all callbacks - var keys = Object.keys(this._callBackStore._notReplied); - // For each key check if it's a callback that needs to be returned - for(var j = 0; j < keys.length; j++) { - var info = this._callBackStore._notReplied[keys[j]]; - // Execute callback with error - this._callBackStore.emit(keys[j], err, null); - // Remove the key - delete this._callBackStore._notReplied[keys[j]]; - // Force cleanup _events, node.js seems to set it as a null value - if(this._callBackStore._events) { - delete this._callBackStore._events[keys[j]]; - } - } -} - -/** - * Fire all the errors - * @ignore - */ -Base.prototype.__executeAllServerSpecificErrorCallbacks = function(host, port, err) { - // Check all callbacks - var keys = Object.keys(this._callBackStore._notReplied); - // For each key check if it's a callback that needs to be returned - for(var j = 0; j < keys.length; j++) { - var info = this._callBackStore._notReplied[keys[j]]; - - if(info && info.connection) { - // Unpack the connection settings - var _host = info.connection.socketOptions.host; - var _port = info.connection.socketOptions.port; - // If the server matches execute the callback with the error - if(_port == port && _host == host) { - this._callBackStore.emit(keys[j], err, null); - // Remove the key - delete this._callBackStore._notReplied[keys[j]]; - // Force cleanup _events, node.js seems to set it as a null value - if(this._callBackStore._events) { - delete this._callBackStore._events[keys[j]]; - } - } - } - } -} - -/** - * Register a handler - * @ignore - * @api private - */ -Base.prototype._registerHandler = function(db_command, raw, connection, exhaust, callback) { - // Check if we have exhausted - if(typeof exhaust == 'function') { - callback = exhaust; - exhaust = false; - } - - // Add the callback to the list of handlers - this._callBackStore.once(db_command.getRequestId(), callback); - // Add the information about the reply - this._callBackStore._notReplied[db_command.getRequestId().toString()] = {start: new Date().getTime(), 'raw': raw, connection:connection, exhaust:exhaust}; -} - -/** - * Re-Register a handler, on the cursor id f.ex - * @ignore - * @api private - */ -Base.prototype._reRegisterHandler = function(newId, object, callback) { - // Add the callback to the list of handlers - this._callBackStore.once(newId, object.callback.listener); - // Add the information about the reply - this._callBackStore._notReplied[newId] = object.info; -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._flushAllCallHandlers = function(err) { - var keys = Object.keys(this._callBackStore._notReplied); - - for(var i = 0; i < keys.length; i++) { - this._callHandler(keys[i], null, err); - } -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._callHandler = function(id, document, err) { - var self = this; - - // If there is a callback peform it - if(this._callBackStore.listeners(id).length >= 1) { - // Get info object - var info = this._callBackStore._notReplied[id]; - // Delete the current object - delete this._callBackStore._notReplied[id]; - // Call the handle directly don't emit - var callback = this._callBackStore.listeners(id)[0].listener; - // Remove the listeners - this._callBackStore.removeAllListeners(id); - // Force key deletion because it nulling it not deleting in 0.10.X - if(this._callBackStore._events) { - delete this._callBackStore._events[id]; - } - - try { - // Execute the callback if one was provided - if(typeof callback == 'function') callback(err, document, info.connection); - } catch(err) { - self._emitAcrossAllDbInstances(self, null, "error", utils.toError(err), self, true, true); - } - } -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._hasHandler = function(id) { - return this._callBackStore.listeners(id).length >= 1; -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._removeHandler = function(id) { - // Remove the information - if(this._callBackStore._notReplied[id] != null) delete this._callBackStore._notReplied[id]; - // Remove the callback if it's registered - this._callBackStore.removeAllListeners(id); - // Force cleanup _events, node.js seems to set it as a null value - if(this._callBackStore._events) { - delete this._callBackStore._events[id]; - } -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._findHandler = function(id) { - var info = this._callBackStore._notReplied[id]; - // Return the callback - return {info:info, callback:(this._callBackStore.listeners(id).length >= 1) ? this._callBackStore.listeners(id)[0] : null} -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._emitAcrossAllDbInstances = function(server, filterDb, event, message, object, resetConnection, rethrow_if_no_listeners) { - if(resetConnection) { - var dbs = this._dbStore.db(); - - for(var i = 0; i < dbs.length; i++) { - if(typeof dbs[i].openCalled != 'undefined') - dbs[i].openCalled = false; - } - } - - // Fire event - this._dbStore.emit(event, message, object, resetConnection, filterDb, rethrow_if_no_listeners); -} - -exports.Base = Base; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/connection.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/connection.js deleted file mode 100755 index 8d9ce77e..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/connection.js +++ /dev/null @@ -1,563 +0,0 @@ -var utils = require('./connection_utils'), - inherits = require('util').inherits, - net = require('net'), - EventEmitter = require('events').EventEmitter, - inherits = require('util').inherits, - binaryutils = require('../utils'), - tls = require('tls'); - -var Connection = exports.Connection = function(id, socketOptions) { - var self = this; - // Set up event emitter - EventEmitter.call(this); - // Store all socket options - this.socketOptions = socketOptions ? socketOptions : {host:'localhost', port:27017, domainSocket:false}; - // Set keep alive default if not overriden - if(this.socketOptions.keepAlive == null && !(process.platform == "sunos" || process.platform == "win32")) this.socketOptions.keepAlive = 100; - // Id for the connection - this.id = id; - // State of the connection - this.connected = false; - // Set if this is a domain socket - this.domainSocket = this.socketOptions.domainSocket; - - // Supported min and max wire protocol - this.minWireVersion = 0; - this.maxWireVersion = 3; - - // - // Connection parsing state - // - this.maxBsonSize = socketOptions.maxBsonSize ? socketOptions.maxBsonSize : Connection.DEFAULT_MAX_BSON_SIZE; - this.maxMessageSizeBytes = socketOptions.maxMessageSizeBytes ? socketOptions.maxMessageSizeBytes : Connection.DEFAULT_MAX_MESSAGE_SIZE; - this.maxNumberOfDocsInBatch = socketOptions.maxWriteBatchSize ? socketOptions.maxWriteBatchSize : Connection.DEFAULT_MAX_WRITE_BATCH_SIZE; - // Contains the current message bytes - this.buffer = null; - // Contains the current message size - this.sizeOfMessage = 0; - // Contains the readIndex for the messaage - this.bytesRead = 0; - // Contains spill over bytes from additional messages - this.stubBuffer = 0; - - // Just keeps list of events we allow - this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[], end:[]}; - - // Just keeps list of events we allow - resetHandlers(this, false); - - // Bson object - this.maxBsonSettings = { - disableDriverBSONSizeCheck: this.socketOptions['disableDriverBSONSizeCheck'] || false - , maxBsonSize: this.maxBsonSize - , maxMessageSizeBytes: this.maxMessageSizeBytes - } - - // Allow setting the socketTimeoutMS on all connections - // to work around issues such as secondaries blocking due to compaction - Object.defineProperty(this, "socketTimeoutMS", { - enumerable: true - , get: function () { return self.socketOptions.socketTimeoutMS; } - , set: function (value) { - // Set the socket timeoutMS value - self.socketOptions.socketTimeoutMS = value; - // Set the physical connection timeout - self.connection.setTimeout(self.socketOptions.socketTimeoutMS); - } - }); -} - -// Set max bson size -Connection.DEFAULT_MAX_BSON_SIZE = 1024 * 1024 * 4; -// Set default to max bson to avoid overflow or bad guesses -Connection.DEFAULT_MAX_MESSAGE_SIZE = Connection.DEFAULT_MAX_BSON_SIZE; -// Max default write bulk ops -Connection.DEFAULT_MAX_WRITE_BATCH_SIZE = 2000; - -// Inherit event emitter so we can emit stuff wohoo -inherits(Connection, EventEmitter); - -Connection.prototype.start = function() { - var self = this; - - // If we have a normal connection - if(this.socketOptions.ssl) { - // Create new connection instance - if(this.domainSocket) { - this.connection = net.createConnection(this.socketOptions.host); - } else { - this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host); - } - if(this.logger != null && this.logger.doDebug){ - this.logger.debug("opened connection", this.socketOptions); - } - - // Set options on the socket - this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout); - // Work around for 0.4.X - if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay); - // Set keep alive if defined - if(process.version.indexOf("v0.4") == -1) { - if(this.socketOptions.keepAlive > 0) { - this.connection.setKeepAlive(true, this.socketOptions.keepAlive); - } else { - this.connection.setKeepAlive(false); - } - } - - // Check if the driver should validate the certificate - var validate_certificates = this.socketOptions.sslValidate == true ? true : false; - - // Create options for the tls connection - var tls_options = { - socket: this.connection - , rejectUnauthorized: false - } - - // If we wish to validate the certificate we have provided a ca store - if(validate_certificates) { - tls_options.ca = this.socketOptions.sslCA; - } - - // If we have a certificate to present - if(this.socketOptions.sslCert) { - tls_options.cert = this.socketOptions.sslCert; - tls_options.key = this.socketOptions.sslKey; - } - - // If the driver has been provided a private key password - if(this.socketOptions.sslPass) { - tls_options.passphrase = this.socketOptions.sslPass; - } - - // Contains the cleartext stream - var cleartext = null; - // Attempt to establish a TLS connection to the server - try { - cleartext = tls.connect(this.socketOptions.port, this.socketOptions.host, tls_options, function() { - // If we have a ssl certificate validation error return an error - if(cleartext.authorizationError && validate_certificates) { - // Emit an error - return self.emit("error", cleartext.authorizationError, self, {ssl:true}); - } - - // Connect to the server - connectHandler(self)(); - }) - } catch(err) { - return self.emit("error", "SSL connection failed", self, {ssl:true}); - } - - // Save the output stream - this.writeSteam = cleartext; - - // Set up data handler for the clear stream - cleartext.on("data", createDataHandler(this)); - // Do any handling of end event of the stream - cleartext.on("end", endHandler(this)); - cleartext.on("error", errorHandler(this)); - - // Handle any errors - this.connection.on("error", errorHandler(this)); - // Handle timeout - this.connection.on("timeout", timeoutHandler(this)); - // Handle drain event - this.connection.on("drain", drainHandler(this)); - // Handle the close event - this.connection.on("close", closeHandler(this)); - } else { - // Create new connection instance - if(this.domainSocket) { - this.connection = net.createConnection(this.socketOptions.host); - } else { - this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host); - } - if(this.logger != null && this.logger.doDebug){ - this.logger.debug("opened connection", this.socketOptions); - } - - // Set options on the socket - this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout); - // Work around for 0.4.X - if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay); - // Set keep alive if defined - if(process.version.indexOf("v0.4") == -1) { - if(this.socketOptions.keepAlive > 0) { - this.connection.setKeepAlive(true, this.socketOptions.keepAlive); - } else { - this.connection.setKeepAlive(false); - } - } - - // Set up write stream - this.writeSteam = this.connection; - // Add handlers - this.connection.on("error", errorHandler(this)); - // Add all handlers to the socket to manage it - this.connection.on("connect", connectHandler(this)); - // this.connection.on("end", endHandler(this)); - this.connection.on("data", createDataHandler(this)); - this.connection.on("timeout", timeoutHandler(this)); - this.connection.on("drain", drainHandler(this)); - this.connection.on("close", closeHandler(this)); - } -} - -/** - * @ignore - */ -Connection.prototype.setSocketOptions = function(options) { - options = options || {}; - - if(typeof options.connectTimeoutMS == 'number') { - this.socketOptions.connectTimeoutMS = options.connectTimeoutMS; - } - - if(typeof options.socketTimeoutMS == 'number') { - this.socketOptions.socketTimeoutMS = options.socketTimeoutMS; - // Set the current socket timeout - this.connection.setTimeout(options.socketTimeoutMS); - } -} - -// Check if the sockets are live -Connection.prototype.isConnected = function() { - return this.connected && !this.connection.destroyed && this.connection.writable; -} - -// Validate if the driver supports this server -Connection.prototype.isCompatible = function() { - if(this.serverCapabilities == null) return true; - - // Is compatible with backward server - if(this.serverCapabilities.minWireVersion == 0 - && this.serverCapabilities.maxWireVersion ==0) return true; - - // Check if we overlap - if(this.serverCapabilities.minWireVersion >= this.minWireVersion - && this.serverCapabilities.maxWireVersion <= this.maxWireVersion) return true; - - // Not compatible - return false; -} - -// Write the data out to the socket -Connection.prototype.write = function(command, callback) { - try { - // If we have a list off commands to be executed on the same socket - if(Array.isArray(command)) { - for(var i = 0; i < command.length; i++) { - try { - // Pass in the bson validation settings (validate early) - var binaryCommand = command[i].toBinary(this.maxBsonSettings); - - if(this.logger != null && this.logger.doDebug) - this.logger.debug("writing command to mongodb", {binary: binaryCommand, json: command[i]}); - - this.writeSteam.write(binaryCommand); - } catch(err) { - return callback(err, null); - } - } - } else { - try { - // Pass in the bson validation settings (validate early) - var binaryCommand = command.toBinary(this.maxBsonSettings); - // Do we have a logger active log the event - if(this.logger != null && this.logger.doDebug) - this.logger.debug("writing command to mongodb", {binary: binaryCommand, json: command}); - // Write the binary command out to socket - this.writeSteam.write(binaryCommand); - } catch(err) { - return callback(err, null); - } - } - } catch (err) { - if(typeof callback === 'function') callback(err); - } -} - -// Force the closure of the connection -Connection.prototype.close = function() { - // clear out all the listeners - resetHandlers(this, true); - // Add a dummy error listener to catch any weird last moment errors (and ignore them) - this.connection.on("error", function() {}) - // destroy connection - this.connection.destroy(); - if(this.logger != null && this.logger.doDebug){ - this.logger.debug("closed connection", this.connection); - } -} - -// Reset all handlers -var resetHandlers = function(self, clearListeners) { - self.eventHandlers = {error:[], connect:[], close:[], end:[], timeout:[], parseError:[], message:[]}; - - // If we want to clear all the listeners - if(clearListeners && self.connection != null) { - var keys = Object.keys(self.eventHandlers); - // Remove all listeners - for(var i = 0; i < keys.length; i++) { - self.connection.removeAllListeners(keys[i]); - } - } -} - -// -// Handlers -// - -// Connect handler -var connectHandler = function(self) { - return function(data) { - // Set connected - self.connected = true; - // Now that we are connected set the socket timeout - self.connection.setTimeout(self.socketOptions.socketTimeoutMS != null ? self.socketOptions.socketTimeoutMS : self.socketOptions.timeout); - // Emit the connect event with no error - self.emit("connect", null, self); - } -} - -var createDataHandler = exports.Connection.createDataHandler = function(self) { - // We need to handle the parsing of the data - // and emit the messages when there is a complete one - return function(data) { - // Parse until we are done with the data - while(data.length > 0) { - // If we still have bytes to read on the current message - if(self.bytesRead > 0 && self.sizeOfMessage > 0) { - // Calculate the amount of remaining bytes - var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; - // Check if the current chunk contains the rest of the message - if(remainingBytesToRead > data.length) { - // Copy the new data into the exiting buffer (should have been allocated when we know the message size) - data.copy(self.buffer, self.bytesRead); - // Adjust the number of bytes read so it point to the correct index in the buffer - self.bytesRead = self.bytesRead + data.length; - - // Reset state of buffer - data = new Buffer(0); - } else { - // Copy the missing part of the data into our current buffer - data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); - // Slice the overflow into a new buffer that we will then re-parse - data = data.slice(remainingBytesToRead); - - // Emit current complete message - try { - var emitBuffer = self.buffer; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Emit the buffer - self.emit("message", emitBuffer, self); - } catch(err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } - } else { - // Stub buffer is kept in case we don't get enough bytes to determine the - // size of the message (< 4 bytes) - if(self.stubBuffer != null && self.stubBuffer.length > 0) { - - // If we have enough bytes to determine the message size let's do it - if(self.stubBuffer.length + data.length > 4) { - // Prepad the data - var newData = new Buffer(self.stubBuffer.length + data.length); - self.stubBuffer.copy(newData, 0); - data.copy(newData, self.stubBuffer.length); - // Reassign for parsing - data = newData; - - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - - } else { - - // Add the the bytes to the stub buffer - var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); - // Copy existing stub buffer - self.stubBuffer.copy(newStubBuffer, 0); - // Copy missing part of the data - data.copy(newStubBuffer, self.stubBuffer.length); - // Exit parsing loop - data = new Buffer(0); - } - } else { - if(data.length > 4) { - // Retrieve the message size - var sizeOfMessage = binaryutils.decodeUInt32(data, 0); - // If we have a negative sizeOfMessage emit error and return - if(sizeOfMessage < 0 || sizeOfMessage > self.maxMessageSizeBytes) { - var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ - sizeOfMessage: sizeOfMessage, - bytesRead: self.bytesRead, - stubBuffer: self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - return; - } - - // Ensure that the size of message is larger than 0 and less than the max allowed - if(sizeOfMessage > 4 && sizeOfMessage < self.maxMessageSizeBytes && sizeOfMessage > data.length) { - self.buffer = new Buffer(sizeOfMessage); - // Copy all the data into the buffer - data.copy(self.buffer, 0); - // Update bytes read - self.bytesRead = data.length; - // Update sizeOfMessage - self.sizeOfMessage = sizeOfMessage; - // Ensure stub buffer is null - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - - } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxMessageSizeBytes && sizeOfMessage == data.length) { - try { - var emitBuffer = data; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - // Emit the message - self.emit("message", emitBuffer, self); - } catch (err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxMessageSizeBytes) { - var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ - sizeOfMessage:sizeOfMessage, - bytesRead:0, - buffer:null, - stubBuffer:null}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - - // Clear out the state of the parser - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - - } else { - try { - var emitBuffer = data.slice(0, sizeOfMessage); - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Copy rest of message - data = data.slice(sizeOfMessage); - // Emit the message - self.emit("message", emitBuffer, self); - } catch (err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - - } - } else { - // Create a buffer that contains the space for the non-complete message - self.stubBuffer = new Buffer(data.length) - // Copy the data to the stub buffer - data.copy(self.stubBuffer, 0); - // Exit parsing loop - data = new Buffer(0); - } - } - } - } - } -} - -var endHandler = function(self) { - return function() { - // Set connected to false - self.connected = false; - // Emit end event - self.emit("end", {err: 'connection received Fin packet from [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } -} - -var timeoutHandler = function(self) { - return function() { - // Set connected to false - self.connected = false; - // Emit timeout event - self.emit("timeout", {err: 'connection to [' + self.socketOptions.host + ':' + self.socketOptions.port + '] timed out'}, self); - } -} - -var drainHandler = function(self) { - return function() { - } -} - -var errorHandler = function(self) { - return function(err) { - self.connection.destroy(); - // Set connected to false - self.connected = false; - // Emit error - self.emit("error", {err: 'failed to connect to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } -} - -var closeHandler = function(self) { - return function(hadError) { - // If we have an error during the connection phase - if(hadError && !self.connected) { - // Set disconnected - self.connected = false; - // Emit error - self.emit("error", {err: 'failed to connect to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } else { - // Set disconnected - self.connected = false; - // Emit close - self.emit("close", {err: 'connection closed to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } - } -} - -// Some basic defaults -Connection.DEFAULT_PORT = 27017; - - - - - - - diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/connection_pool.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/connection_pool.js deleted file mode 100755 index 8fd2932f..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/connection_pool.js +++ /dev/null @@ -1,311 +0,0 @@ -var utils = require('./connection_utils'), - inherits = require('util').inherits, - net = require('net'), - timers = require('timers'), - EventEmitter = require('events').EventEmitter, - inherits = require('util').inherits, - MongoReply = require("../responses/mongo_reply").MongoReply, - Connection = require("./connection").Connection; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -var ConnectionPool = exports.ConnectionPool = function(host, port, poolSize, bson, socketOptions) { - if(typeof host !== 'string') { - throw new Error("host must be specified [" + host + "]"); - } - - // Set up event emitter - EventEmitter.call(this); - - // Keep all options for the socket in a specific collection allowing the user to specify the - // Wished upon socket connection parameters - this.socketOptions = typeof socketOptions === 'object' ? socketOptions : {}; - this.socketOptions.host = host; - this.socketOptions.port = port; - this.socketOptions.domainSocket = false; - this.bson = bson; - // PoolSize is always + 1 for special reserved "measurment" socket (like ping, stats etc) - if (typeof poolSize !== 'number') { - poolSize = parseInt(poolSize.toString(), 10); - if (isNaN(poolSize)) { - throw new Error("poolSize must be a number!"); - } - } - this.poolSize = poolSize; - this.minPoolSize = Math.floor(this.poolSize / 2) + 1; - - // Check if the host is a socket - if(host.match(/^\//)) { - this.socketOptions.domainSocket = true; - } else if(typeof port === 'string') { - try { - port = parseInt(port, 10); - } catch(err) { - new Error("port must be specified or valid integer[" + port + "]"); - } - } else if(typeof port !== 'number') { - throw new Error("port must be specified [" + port + "]"); - } - - // Set default settings for the socket options - utils.setIntegerParameter(this.socketOptions, 'timeout', 0); - // Delay before writing out the data to the server - utils.setBooleanParameter(this.socketOptions, 'noDelay', true); - // Delay before writing out the data to the server - utils.setIntegerParameter(this.socketOptions, 'keepAlive', 0); - // Set the encoding of the data read, default is binary == null - utils.setStringParameter(this.socketOptions, 'encoding', null); - // Allows you to set a throttling bufferSize if you need to stop overflows - utils.setIntegerParameter(this.socketOptions, 'bufferSize', 0); - - // Internal structures - this.openConnections = []; - // Assign connection id's - this.connectionId = 0; - - // Current index for selection of pool connection - this.currentConnectionIndex = 0; - // The pool state - this._poolState = 'disconnected'; - // timeout control - this._timeout = false; - // Time to wait between connections for the pool - this._timeToWait = 10; -} - -inherits(ConnectionPool, EventEmitter); - -ConnectionPool.prototype.setMaxBsonSize = function(maxBsonSize) { - if(maxBsonSize == null){ - maxBsonSize = Connection.DEFAULT_MAX_BSON_SIZE; - } - - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].maxBsonSize = maxBsonSize; - this.openConnections[i].maxBsonSettings.maxBsonSize = maxBsonSize; - } -} - -ConnectionPool.prototype.setMaxMessageSizeBytes = function(maxMessageSizeBytes) { - if(maxMessageSizeBytes == null){ - maxMessageSizeBytes = Connection.DEFAULT_MAX_MESSAGE_SIZE; - } - - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].maxMessageSizeBytes = maxMessageSizeBytes; - this.openConnections[i].maxBsonSettings.maxMessageSizeBytes = maxMessageSizeBytes; - } -} - -ConnectionPool.prototype.setMaxWriteBatchSize = function(maxWriteBatchSize) { - if(maxWriteBatchSize == null){ - maxWriteBatchSize = Connection.DEFAULT_MAX_WRITE_BATCH_SIZE; - } - - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].maxWriteBatchSize = maxWriteBatchSize; - } -} - -// Start a function -var _connect = function(_self) { - // return new function() { - // Create a new connection instance - var connection = new Connection(_self.connectionId++, _self.socketOptions); - // Set logger on pool - connection.logger = _self.logger; - // Connect handler - connection.on("connect", function(err, connection) { - // Add connection to list of open connections - _self.openConnections.push(connection); - // If the number of open connections is equal to the poolSize signal ready pool - if(_self.openConnections.length === _self.poolSize && _self._poolState !== 'disconnected') { - // Set connected - _self._poolState = 'connected'; - // Emit pool ready - _self.emit("poolReady"); - } else if(_self.openConnections.length < _self.poolSize) { - // Wait a little bit of time to let the close event happen if the server closes the connection - // so we don't leave hanging connections around - if(typeof _self._timeToWait == 'number') { - setTimeout(function() { - // If we are still connecting (no close events fired in between start another connection) - if(_self._poolState == 'connecting') { - _connect(_self); - } - }, _self._timeToWait); - } else { - processor(function() { - // If we are still connecting (no close events fired in between start another connection) - if(_self._poolState == 'connecting') { - _connect(_self); - } - }); - } - } - }); - - var numberOfErrors = 0 - - // Error handler - connection.on("error", function(err, connection, error_options) { - numberOfErrors++; - // If we are already disconnected ignore the event - if(_self._poolState != 'disconnected' && _self.listeners("error").length > 0) { - _self.emit("error", err, connection, error_options); - } - - // Close the connection - connection.close(); - // Set pool as disconnected - _self._poolState = 'disconnected'; - // Stop the pool - _self.stop(); - }); - - // Close handler - connection.on("close", function() { - // If we are already disconnected ignore the event - if(_self._poolState !== 'disconnected' && _self.listeners("close").length > 0) { - _self.emit("close"); - } - - // Set disconnected - _self._poolState = 'disconnected'; - // Stop - _self.stop(); - }); - - // Timeout handler - connection.on("timeout", function(err, connection) { - // If we are already disconnected ignore the event - if(_self._poolState !== 'disconnected' && _self.listeners("timeout").length > 0) { - _self.emit("timeout", err); - } - - // Close the connection - connection.close(); - // Set disconnected - _self._poolState = 'disconnected'; - _self.stop(); - }); - - // Parse error, needs a complete shutdown of the pool - connection.on("parseError", function() { - // If we are already disconnected ignore the event - if(_self._poolState !== 'disconnected' && _self.listeners("parseError").length > 0) { - _self.emit("parseError", new Error("parseError occured")); - } - - // Set disconnected - _self._poolState = 'disconnected'; - _self.stop(); - }); - - connection.on("message", function(message) { - _self.emit("message", message); - }); - - // Start connection in the next tick - connection.start(); - // }(); -} - - -// Start method, will throw error if no listeners are available -// Pass in an instance of the listener that contains the api for -// finding callbacks for a given message etc. -ConnectionPool.prototype.start = function() { - var markerDate = new Date().getTime(); - var self = this; - - if(this.listeners("poolReady").length == 0) { - throw "pool must have at least one listener ready that responds to the [poolReady] event"; - } - - // Set pool state to connecting - this._poolState = 'connecting'; - this._timeout = false; - - _connect(self); -} - -// Restart a connection pool (on a close the pool might be in a wrong state) -ConnectionPool.prototype.restart = function() { - // Close all connections - this.stop(false); - // Now restart the pool - this.start(); -} - -// Stop the connections in the pool -ConnectionPool.prototype.stop = function(removeListeners) { - removeListeners = removeListeners == null ? true : removeListeners; - // Set disconnected - this._poolState = 'disconnected'; - - // Clear all listeners if specified - if(removeListeners) { - this.removeAllEventListeners(); - } - - // Close all connections - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].close(); - } - - // Clean up - this.openConnections = []; -} - -// Check the status of the connection -ConnectionPool.prototype.isConnected = function() { - // return this._poolState === 'connected'; - return this.openConnections.length > 0 && this.openConnections[0].isConnected(); -} - -// Checkout a connection from the pool for usage, or grab a specific pool instance -ConnectionPool.prototype.checkoutConnection = function(id) { - var index = (this.currentConnectionIndex++ % (this.openConnections.length)); - var connection = this.openConnections[index]; - return connection; -} - -ConnectionPool.prototype.getAllConnections = function() { - return this.openConnections; -} - -// Remove all non-needed event listeners -ConnectionPool.prototype.removeAllEventListeners = function() { - this.removeAllListeners("close"); - this.removeAllListeners("error"); - this.removeAllListeners("timeout"); - this.removeAllListeners("connect"); - this.removeAllListeners("end"); - this.removeAllListeners("parseError"); - this.removeAllListeners("message"); - this.removeAllListeners("poolReady"); -} - - - - - - - - - - - - - - - - - - - - - - diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/connection_utils.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/connection_utils.js deleted file mode 100755 index 59109249..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/connection_utils.js +++ /dev/null @@ -1,23 +0,0 @@ -exports.setIntegerParameter = function(object, field, defaultValue) { - if(object[field] == null) { - object[field] = defaultValue; - } else if(typeof object[field] !== "number" && object[field] !== parseInt(object[field], 10)) { - throw "object field [" + field + "] must be a numeric integer value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]"; - } -} - -exports.setBooleanParameter = function(object, field, defaultValue) { - if(object[field] == null) { - object[field] = defaultValue; - } else if(typeof object[field] !== "boolean") { - throw "object field [" + field + "] must be a boolean value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]"; - } -} - -exports.setStringParameter = function(object, field, defaultValue) { - if(object[field] == null) { - object[field] = defaultValue; - } else if(typeof object[field] !== "string") { - throw "object field [" + field + "] must be a string value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]"; - } -} \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/mongos.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/mongos.js deleted file mode 100755 index 8c0a4f20..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/mongos.js +++ /dev/null @@ -1,603 +0,0 @@ -var ReadPreference = require('./read_preference').ReadPreference - , Base = require('./base').Base - , ServerCapabilities = require('./server_capabilities').ServerCapabilities - , Server = require('./server').Server - , format = require('util').format - , timers = require('timers') - , utils = require('../utils') - , inherits = require('util').inherits; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - * Mongos constructor provides a connection to a mongos proxy including failover to additional servers - * - * Options - * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number)) - * - **ha** {Boolean, default:true}, turn on high availability, attempts to reconnect to down proxies - * - **haInterval** {Number, default:2000}, time between each replicaset status check. - * - * @class Represents a Mongos connection with failover to backup proxies - * @param {Array} list of mongos server objects - * @param {Object} [options] additional options for the mongos connection - */ -var Mongos = function Mongos(servers, options) { - // Set up basic - if(!(this instanceof Mongos)) - return new Mongos(servers, options); - - // Set up event emitter - Base.call(this); - - // Throw error on wrong setup - if(servers == null || !Array.isArray(servers) || servers.length == 0) - throw new Error("At least one mongos proxy must be in the array"); - - // Ensure we have at least an empty options object - this.options = options == null ? {} : options; - // Set default connection pool options - this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {}; - // Enabled ha - this.haEnabled = this.options['ha'] == null ? true : this.options['ha']; - this._haInProgress = false; - // How often are we checking for new servers in the replicaset - this.mongosStatusCheckInterval = this.options['haInterval'] == null ? 1000 : this.options['haInterval']; - // Save all the server connections - this.servers = servers; - // Servers we need to attempt reconnect with - this.downServers = {}; - // Servers that are up - this.upServers = {}; - // Up servers by ping time - this.upServersByUpTime = {}; - // Set poolsize or default - this.poolSize = this.options.poolSize || 5; - // Emit open setup - this.emitOpen = this.options.emitOpen || true; - // Just contains the current lowest ping time and server - this.lowestPingTimeServer = null; - this.lowestPingTime = 0; - // Connection timeout - this._connectTimeoutMS = this.socketOptions.connectTimeoutMS - ? this.socketOptions.connectTimeoutMS - : 1000; - - // Add options to servers - for(var i = 0; i < this.servers.length; i++) { - var server = this.servers[i]; - server._callBackStore = this._callBackStore; - server.auto_reconnect = false; - - // Override pool size - if(typeof this.poolSize == 'number') { - server.poolSize = this.poolSize - } - - // Default empty socket options object - var socketOptions = {host: server.host, port: server.port}; - // If a socket option object exists clone it - if(this.socketOptions != null) { - var keys = Object.keys(this.socketOptions); - for(var k = 0; k < keys.length;k++) socketOptions[keys[i]] = this.socketOptions[keys[i]]; - } - - // Set socket options - server.socketOptions = socketOptions; - } - - // Allow setting the socketTimeoutMS on all connections - // to work around issues such as secondaries blocking due to compaction - utils.setSocketTimeoutProperty(this, this.socketOptions); -} - -/** - * @ignore - */ -inherits(Mongos, Base); - -/** - * @ignore - */ -Mongos.prototype.isMongos = function() { - return true; -} - -/** - * @ignore - */ -Mongos.prototype.connect = function(db, options, callback) { - if('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - var self = this; - - // Keep reference to parent - this.db = db; - // Set server state to connecting - this._serverState = 'connecting'; - // Number of total servers that need to initialized (known servers) - this._numberOfServersLeftToInitialize = this.servers.length; - // Connect handler - var connectHandler = function(_server) { - return function(err, result) { - self._numberOfServersLeftToInitialize = self._numberOfServersLeftToInitialize - 1; - - // Add server capabilities - if(_server.isMasterDoc) { - // Set server capabilities - _server.serverCapabilities = new ServerCapabilities(_server.isMasterDoc); - - // Set server capabilities on all the connections - var connections = _server.allRawConnections(); - for(var i = 0; i < connections.length; i++) { - connections[i].serverCapabilities = _server.serverCapabilities; - } - } - - // Add the server to the list of servers that are up - if(!err) { - self.upServers[format("%s:%s", _server.host, _server.port)] = _server; - } - - // We are done connecting - if(self._numberOfServersLeftToInitialize == 0) { - // If we have no valid mongos server instances error out - if(Object.keys(self.upServers).length == 0) { - // return self.emit("connectionError", new Error("No valid mongos instances found")); - return callback(new Error("No valid mongos instances found"), null); - } - - // Start ha function if it exists - if(self.haEnabled) { - // Setup the ha process - if(self._replicasetTimeoutId != null) clearInterval(self._replicasetTimeoutId); - self._replicasetTimeoutId = setInterval(self.mongosCheckFunction, self.mongosStatusCheckInterval); - } - - // Set the mongos to connected - self._serverState = "connected"; - - // Emit the open event - if(self.emitOpen) - self._emitAcrossAllDbInstances(self, null, "open", null, null, null); - - self._emitAcrossAllDbInstances(self, null, "fullsetup", null, null, null); - // Callback - callback(null, self.db); - } - } - }; - - // Error handler - var errorOrCloseHandler = function(_server) { - return function(err, result) { - // Emit left event, signaling mongos left the ha - self.emit('left', 'mongos', _server); - // Execute all the callbacks with errors - self.__executeAllCallbacksWithError(err); - // Check if we have the server - var found = false; - - // Get the server name - var server_name = format("%s:%s", _server.host, _server.port); - // Add the downed server - self.downServers[server_name] = _server; - // Remove the current server from the list - delete self.upServers[server_name]; - - // Emit close across all the attached db instances - if(Object.keys(self.upServers).length == 0) { - self._emitAcrossAllDbInstances(self, null, "close", new Error("mongos disconnected, no valid proxies contactable over tcp"), null, null); - } - } - } - - // Mongo function - this.mongosCheckFunction = function() { - // Set as not waiting for check event - self._haInProgress = true; - - // Servers down - var numberOfServersLeft = Object.keys(self.downServers).length; - - // Check downed servers - if(numberOfServersLeft > 0) { - for(var name in self.downServers) { - // Pop a downed server - var downServer = self.downServers[name]; - // Set up the connection options for a Mongos - var options = { - auto_reconnect: false, - returnIsMasterResults: true, - slaveOk: true, - poolSize: self.poolSize, - socketOptions: { - connectTimeoutMS: self._connectTimeoutMS, - socketTimeoutMS: self._socketTimeoutMS - } - } - - // Create a new server object - var newServer = new Server(downServer.host, downServer.port, options); - // Setup the connection function - var connectFunction = function(_db, _server, _options, _callback) { - return function() { - // Attempt to connect - _server.connect(_db, _options, function(err, result) { - numberOfServersLeft = numberOfServersLeft - 1; - - // Add server capabilities - if(_server.isMasterDoc) { - // Set server capabilities - _server.serverCapabilities = new ServerCapabilities(_server.isMasterDoc); - - // Set server capabilities on all the connections - var connections = _server.allRawConnections(); - for(var i = 0; i < connections.length; i++) { - connections[i].serverCapabilities = _server.serverCapabilities; - } - } - - if(err) { - return _callback(err, _server); - } else { - // Set the new server settings - _server._callBackStore = self._callBackStore; - - // Add server event handlers - _server.on("close", errorOrCloseHandler(_server)); - _server.on("timeout", errorOrCloseHandler(_server)); - _server.on("error", errorOrCloseHandler(_server)); - - // Get a read connection - var _connection = _server.checkoutReader(); - // Get the start time - var startTime = new Date().getTime(); - - // Execute ping command to mark each server with the expected times - self.db.command({ping:1} - , {failFast:true, connection:_connection}, function(err, result) { - // Get the start time - var endTime = new Date().getTime(); - // Mark the server with the ping time - _server.runtimeStats['pingMs'] = endTime - startTime; - - // If we have any buffered commands let's signal reconnect event - if(self._commandsStore.count() > 0) { - self.emit('reconnect'); - } - - // Execute any waiting reads - self._commandsStore.execute_writes(); - self._commandsStore.execute_queries(); - // Callback - return _callback(null, _server); - }); - } - }); - } - } - - // Attempt to connect to the database - connectFunction(self.db, newServer, options, function(err, _server) { - // If we have an error - if(err) { - self.downServers[format("%s:%s", _server.host, _server.port)] = _server; - } - - // Connection function - var connectionFunction = function(_auth, _connection, _callback) { - var pending = _auth.length(); - - for(var j = 0; j < pending; j++) { - // Get the auth object - var _auth = _auth.get(j); - // Unpack the parameter - var username = _auth.username; - var password = _auth.password; - var options = { - authMechanism: _auth.authMechanism - , authSource: _auth.authdb - , connection: _connection - }; - - // If we have changed the service name - if(_auth.gssapiServiceName) - options.gssapiServiceName = _auth.gssapiServiceName; - - // Hold any error - var _error = null; - // Authenticate against the credentials - self.db.authenticate(username, password, options, function(err, result) { - _error = err != null ? err : _error; - // Adjust the pending authentication - pending = pending - 1; - // Finished up - if(pending == 0) _callback(_error ? _error : null, _error ? false : true); - }); - } - } - - // Run auths against the connections - if(self.auth.length() > 0) { - var connections = _server.allRawConnections(); - var pendingAuthConn = connections.length; - - // No connections we are done - if(connections.length == 0) { - // Set ha done - if(numberOfServersLeft == 0) { - self._haInProgress = false; - } - } - - // Final error object - var finalError = null; - // Go over all the connections - for(var j = 0; j < connections.length; j++) { - - // Execute against all the connections - connectionFunction(self.auth, connections[j], function(err, result) { - // Pending authentication - pendingAuthConn = pendingAuthConn - 1 ; - - // Save error if any - finalError = err ? err : finalError; - - // If we are done let's finish up - if(pendingAuthConn == 0) { - // Set ha done - if(numberOfServersLeft == 0) { - self._haInProgress = false; - } - - if(!err) { - add_server(self, _server); - } - - // If we have any buffered commands let's signal reconnect event - if(self._commandsStore.count() > 0) { - self.emit('reconnect'); - } - - // Execute any waiting reads - self._commandsStore.execute_writes(); - self._commandsStore.execute_queries(); - } - }); - } - } else { - if(!err) { - add_server(self, _server); - } - - // Set ha done - if(numberOfServersLeft == 0) { - self._haInProgress = false; - - // If we have any buffered commands let's signal reconnect event - if(self._commandsStore.count() > 0) { - self.emit('reconnect'); - } - - // Execute any waiting reads - self._commandsStore.execute_writes(); - self._commandsStore.execute_queries(); - } - } - })(); - } - } else { - self._haInProgress = false; - } - } - - // Connect all the server instances - for(var i = 0; i < this.servers.length; i++) { - // Get the connection - var server = this.servers[i]; - server.mongosInstance = this; - // Add server event handlers - server.on("close", errorOrCloseHandler(server)); - server.on("timeout", errorOrCloseHandler(server)); - server.on("error", errorOrCloseHandler(server)); - - // Configuration - var options = { - slaveOk: true, - poolSize: this.poolSize || server.poolSize, - socketOptions: { connectTimeoutMS: self._connectTimeoutMS }, - returnIsMasterResults: true - } - - // Connect the instance - server.connect(self.db, options, connectHandler(server)); - } -} - -/** - * @ignore - * Add a server to the list of up servers and sort them by ping time - */ -var add_server = function(self, _server) { - // Emit a new server joined - self.emit('joined', "mongos", null, _server); - // Get the server url - var server_key = format("%s:%s", _server.host, _server.port); - // Push to list of valid server - self.upServers[server_key] = _server; - // Remove the server from the list of downed servers - delete self.downServers[server_key]; - - // Sort the keys by ping time - var keys = Object.keys(self.upServers); - var _upServersSorted = {}; - var _upServers = [] - - // Get all the servers - for(var name in self.upServers) { - _upServers.push(self.upServers[name]); - } - - // Sort all the server - _upServers.sort(function(a, b) { - return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs']; - }); - - // Rebuild the upServer - for(var i = 0; i < _upServers.length; i++) { - _upServersSorted[format("%s:%s", _upServers[i].host, _upServers[i].port)] = _upServers[i]; - } - - // Set the up servers - self.upServers = _upServersSorted; -} - -/** - * @ignore - * Just return the currently picked active connection - */ -Mongos.prototype.allServerInstances = function() { - return this.servers; -} - -/** - * @ignore - */ -Mongos.prototype.setSocketOptions = function(options) { - var servers = this.allServerInstances(); - for(var i = 0; i < servers.length; i++) { - servers[i].setSocketOptions(options); - } -} - -/** - * Always ourselves - * @ignore - */ -Mongos.prototype.setReadPreference = function() {} - -/** - * @ignore - */ -Mongos.prototype.allRawConnections = function() { - // Neeed to build a complete list of all raw connections, start with master server - var allConnections = []; - // Get all connected connections - for(var name in this.upServers) { - allConnections = allConnections.concat(this.upServers[name].allRawConnections()); - } - // Return all the conections - return allConnections; -} - -/** - * @ignore - */ -Mongos.prototype.isConnected = function() { - return Object.keys(this.upServers).length > 0; -} - -/** - * @ignore - */ -Mongos.prototype.isAutoReconnect = function() { - return true; -} - -/** - * @ignore - */ -Mongos.prototype.canWrite = Mongos.prototype.isConnected; - -/** - * @ignore - */ -Mongos.prototype.canRead = Mongos.prototype.isConnected; - -/** - * @ignore - */ -Mongos.prototype.isDestroyed = function() { - return this._serverState == 'destroyed'; -} - -/** - * @ignore - */ -Mongos.prototype.checkoutWriter = function() { - // Checkout a writer - var keys = Object.keys(this.upServers); - if(keys.length == 0) return null; - return this.upServers[keys[0]].checkoutWriter(); -} - -/** - * @ignore - */ -Mongos.prototype.checkoutReader = function(read) { - // If read is set to null default to primary - read = read || 'primary' - // If we have a read preference object unpack it - if(read != null && typeof read == 'object' && read['_type'] == 'ReadPreference') { - // Validate if the object is using a valid mode - if(!read.isValid()) throw new Error("Illegal readPreference mode specified, " + JSON.stringify(read)); - } else if(!ReadPreference.isValid(read)) { - throw new Error("Illegal readPreference mode specified, " + JSON.stringify(read)); - } - - // Checkout a writer - var keys = Object.keys(this.upServers); - if(keys.length == 0) return null; - return this.upServers[keys[0]].checkoutWriter(); -} - -/** - * @ignore - */ -Mongos.prototype.close = function(callback) { - var self = this; - // Set server status as disconnected - this._serverState = 'destroyed'; - // Number of connections to close - var numberOfConnectionsToClose = self.servers.length; - // If we have a ha process running kill it - if(self._replicasetTimeoutId != null) clearInterval(self._replicasetTimeoutId); - self._replicasetTimeoutId = null; - - // Emit close event - processor(function() { - self._emitAcrossAllDbInstances(self, null, "close", null, null, true) - }); - - // Flush out any remaining call handlers - self._flushAllCallHandlers(utils.toError("Connection Closed By Application")); - - // No up servers just return - if(Object.keys(this.upServers) == 0) { - return callback(null); - } - - // Close all the up servers - for(var name in this.upServers) { - this.upServers[name].close(function(err, result) { - numberOfConnectionsToClose = numberOfConnectionsToClose - 1; - - // Callback if we have one defined - if(numberOfConnectionsToClose == 0 && typeof callback == 'function') { - callback(null); - } - }); - } -} - -/** - * @ignore - * Return the used state - */ -Mongos.prototype._isUsed = function() { - return this._used; -} - -exports.Mongos = Mongos; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/read_preference.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/read_preference.js deleted file mode 100755 index 6caafa95..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/read_preference.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * A class representation of the Read Preference. - * - * Read Preferences - * - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.). - * - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary. - * - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error. - * - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary. - * - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection. - * - * @class Represents a Read Preference. - * @param {String} the read preference type - * @param {Object} tags - * @return {ReadPreference} - */ -var ReadPreference = function(mode, tags) { - if(!(this instanceof ReadPreference)) - return new ReadPreference(mode, tags); - this._type = 'ReadPreference'; - this.mode = mode; - this.tags = tags; -} - -/** - * @ignore - */ -ReadPreference.isValid = function(_mode) { - return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED - || _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED - || _mode == ReadPreference.NEAREST - || _mode == true || _mode == false || _mode == null); -} - -/** - * @ignore - */ -ReadPreference.prototype.isValid = function(mode) { - var _mode = typeof mode == 'string' ? mode : this.mode; - return ReadPreference.isValid(_mode); -} - -/** - * @ignore - */ -ReadPreference.prototype.toObject = function() { - var object = {mode:this.mode}; - - if(this.tags != null) { - object['tags'] = this.tags; - } - - return object; -} - -/** - * @ignore - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest' - -/** - * @ignore - */ -exports.ReadPreference = ReadPreference; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js deleted file mode 100755 index 50db818f..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js +++ /dev/null @@ -1,473 +0,0 @@ -var DbCommand = require('../../commands/db_command').DbCommand - , ServerCapabilities = require('../server_capabilities').ServerCapabilities - , format = require('util').format; - -var HighAvailabilityProcess = function(replset, options) { - this.replset = replset; - this.options = options; - this.server = null; - this.state = HighAvailabilityProcess.INIT; - this.selectedIndex = 0; -} - -HighAvailabilityProcess.INIT = 'init'; -HighAvailabilityProcess.RUNNING = 'running'; -HighAvailabilityProcess.STOPPED = 'stopped'; - -HighAvailabilityProcess.prototype.start = function() { - var self = this; - if(this.replset._state - && Object.keys(this.replset._state.addresses).length == 0) { - if(this.server) this.server.close(); - this.state = HighAvailabilityProcess.STOPPED; - return; - } - - if(this.server) this.server.close(); - // Start the running - this._haProcessInProcess = false; - this.state = HighAvailabilityProcess.RUNNING; - - // Get all possible reader servers - var candidate_servers = this.replset._state.getAllReadServers(); - if(candidate_servers.length == 0) { - return; - } - - // Select a candidate server for the connection - var server = candidate_servers[this.selectedIndex % candidate_servers.length]; - this.selectedIndex = this.selectedIndex + 1; - - // Unpack connection options - var connectTimeoutMS = self.options.connectTimeoutMS || 10000; - var socketTimeoutMS = self.options.socketTimeoutMS || 30000; - - // Just ensure we don't have a full cycle dependency - var Db = require('../../db').Db - var Server = require('../server').Server; - - // Set up a new server instance - var newServer = new Server(server.host, server.port, { - auto_reconnect: false - , returnIsMasterResults: true - , poolSize: 1 - , socketOptions: { - connectTimeoutMS: connectTimeoutMS, - socketTimeoutMS: socketTimeoutMS, - keepAlive: 100 - } - , ssl: self.replset.options.ssl - , sslValidate: self.replset.options.sslValidate - , sslCA: self.replset.options.sslCA - , sslCert: self.replset.options.sslCert - , sslKey: self.replset.options.sslKey - , sslPass: self.replset.options.sslPass - }); - - // Create new dummy db for app - self.db = new Db('local', newServer, {w:1}); - - // Set up the event listeners - newServer.once("error", _handle(this, newServer)); - newServer.once("close", _handle(this, newServer)); - newServer.once("timeout", _handle(this, newServer)); - newServer.name = format("%s:%s", server.host, server.port); - - // Let's attempt a connection over here - newServer.connect(self.db, function(err, result, _server) { - // Emit ha_connect - self.replset.emit("ha_connect", err, result, _server); - - if(self.state == HighAvailabilityProcess.STOPPED) { - _server.close(); - } - - // Ensure server capabilities object is on all connections - if(_server.isMasterDoc) { - // Set server capabilities - _server.serverCapabilities = new ServerCapabilities(_server.isMasterDoc); - - // Set server capabilities on all the connections - var connections = _server.allRawConnections(); - for(var i = 0; i < connections.length; i++) { - connections[i].serverCapabilities = _server.serverCapabilities; - } - } - - if(err) { - // Close the server - _server.close(); - // Check if we can even do HA (is there anything running) - if(Object.keys(self.replset._state.addresses).length == 0) { - return; - } - - // Let's boot the ha timeout settings - setTimeout(function() { - self.start(); - }, self.options.haInterval); - } else { - self.server = _server; - // Let's boot the ha timeout settings - setTimeout(_timeoutHandle(self), self.options.haInterval); - } - }); -} - -HighAvailabilityProcess.prototype.stop = function() { - this.state = HighAvailabilityProcess.STOPPED; - if(this.server) this.server.close(); -} - -var _timeoutHandle = function(self) { - return function() { - if(self.state == HighAvailabilityProcess.STOPPED) { - // Stop all server instances - for(var name in self.replset._state.addresses) { - self.replset._state.addresses[name].close(); - delete self.replset._state.addresses[name]; - } - - // Finished pinging - return; - } - - // If the server is connected - if(self.server.isConnected() && !self._haProcessInProcess) { - // Start HA process - self._haProcessInProcess = true; - // Execute is master command - self.db._executeQueryCommand(DbCommand.createIsMasterCommand(self.db), - {failFast:true, connection: self.server.checkoutReader()} - , function(err, res) { - // Emit ha event - self.replset.emit("ha_ismaster", err, res); - - // If we have an error close - if(err) { - self.server.close(); - // Re-run loop - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - - // Master document - var master = res.documents[0]; - var hosts = master.hosts || []; - var reconnect_servers = []; - var state = self.replset._state; - - // We are in recovery mode, let's remove the current server - if(!master.ismaster - && !master.secondary - && state.addresses[master.me]) { - self.server.close(); - state.addresses[master.me].close(); - delete state.secondaries[master.me]; - // Re-run loop - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - - // We have a new master different front he current one - if((master.primary && state.master == null) - || (master.primary && state.master.name != master.primary)) { - - // Locate the primary and set it - if(state.addresses[master.primary]) { - if(state.master) state.master.close(); - delete state.secondaries[master.primary]; - state.master = state.addresses[master.primary]; - } - - // Emit joined event due to primary change - self.replset.emit('joined', "primary", master, state.master); - - // Set up the changes - if(state.master != null && state.master.isMasterDoc != null) { - state.master.isMasterDoc.ismaster = true; - state.master.isMasterDoc.secondary = false; - } else if(state.master != null) { - state.master.isMasterDoc = master; - state.master.isMasterDoc.ismaster = true; - state.master.isMasterDoc.secondary = false; - } - - // If we have any buffered commands let's signal reconnect event - if(self.replset._commandsStore.count() > 0) { - self.replset.emit('reconnect'); - } - - // Execute any waiting commands (queries or writes) - self.replset._commandsStore.execute_queries(); - self.replset._commandsStore.execute_writes(); - } - - // For all the hosts let's check that we have connections - for(var i = 0; i < hosts.length; i++) { - var host = hosts[i]; - - // Check if we need to reconnect to a server - if(state.addresses[host] == null) { - reconnect_servers.push(host); - } else if(state.addresses[host] && !state.addresses[host].isConnected()) { - state.addresses[host].close(); - delete state.secondaries[host]; - reconnect_servers.push(host); - } - } - - // Let's reconnect to any server needed - if(reconnect_servers.length > 0) { - _reconnect_servers(self, reconnect_servers); - } else { - self._haProcessInProcess = false - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - }); - } else if(!self.server.isConnected()) { - setTimeout(function() { - return self.start(); - }, self.options.haInterval); - } else { - setTimeout(_timeoutHandle(self), self.options.haInterval); - } - } -} - -var _reconnect_servers = function(self, reconnect_servers) { - if(reconnect_servers.length == 0) { - self._haProcessInProcess = false - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - - // Unpack connection options - var connectTimeoutMS = self.options.connectTimeoutMS || 10000; - var socketTimeoutMS = self.options.socketTimeoutMS || 0; - - // Server class - var Db = require('../../db').Db - var Server = require('../server').Server; - // Get the host - var host = reconnect_servers.shift(); - // Split it up - var _host = host.split(":")[0]; - var _port = parseInt(host.split(":")[1], 10); - - // Set up a new server instance - var newServer = new Server(_host, _port, { - auto_reconnect: false - , returnIsMasterResults: true - , poolSize: self.options.poolSize - , socketOptions: { - connectTimeoutMS: connectTimeoutMS, - socketTimeoutMS: socketTimeoutMS - } - , ssl: self.replset.options.ssl - , sslValidate: self.replset.options.sslValidate - , sslCA: self.replset.options.sslCA - , sslCert: self.replset.options.sslCert - , sslKey: self.replset.options.sslKey - , sslPass: self.replset.options.sslPass - }); - - // Create new dummy db for app - var db = new Db('local', newServer, {w:1}); - var state = self.replset._state; - - // Set up the event listeners - newServer.once("error", _repl_set_handler("error", self.replset, newServer)); - newServer.once("close", _repl_set_handler("close", self.replset, newServer)); - newServer.once("timeout", _repl_set_handler("timeout", self.replset, newServer)); - - // Set shared state - newServer.name = host; - newServer._callBackStore = self.replset._callBackStore; - newServer.replicasetInstance = self.replset; - newServer.enableRecordQueryStats(self.replset.recordQueryStats); - - // Let's attempt a connection over here - newServer.connect(db, function(err, result, _server) { - // Emit ha_connect - self.replset.emit("ha_connect", err, result, _server); - - if(self.state == HighAvailabilityProcess.STOPPED) { - _server.close(); - } - - // Ensure server capabilities object is on all connections - if(_server.isMasterDoc) { - // Set server capabilities - _server.serverCapabilities = new ServerCapabilities(_server.isMasterDoc); - - // Set server capabilities on all the connections - var connections = _server.allRawConnections(); - for(var i = 0; i < connections.length; i++) { - connections[i].serverCapabilities = _server.serverCapabilities; - } - } - - // If we connected let's check what kind of server we have - if(!err) { - _apply_auths(self, db, _server, function(err, result) { - if(err) { - _server.close(); - // Process the next server - return setTimeout(function() { - _reconnect_servers(self, reconnect_servers); - }, self.options.haInterval); - } - - var doc = _server.isMasterDoc; - // Fire error on any unknown callbacks for this server - self.replset.__executeAllServerSpecificErrorCallbacks(_server.socketOptions.host, _server.socketOptions.port, err); - - if(doc.ismaster) { - // Emit primary added - self.replset.emit('joined', "primary", doc, _server); - - // If it was a secondary remove it - if(state.secondaries[doc.me]) { - delete state.secondaries[doc.me]; - } - - // Override any server in list of addresses - state.addresses[doc.me] = _server; - // Set server as master - state.master = _server; - - // If we have any buffered commands let's signal reconnect event - if(self.replset._commandsStore.count() > 0) { - self.replset.emit('reconnect'); - } - - // Execute any waiting writes - self.replset._commandsStore.execute_writes(); - } else if(doc.secondary) { - // Emit secondary added - self.replset.emit('joined', "secondary", doc, _server); - // Add the secondary to the state - state.secondaries[doc.me] = _server; - // Override any server in list of addresses - state.addresses[doc.me] = _server; - - // If we have any buffered commands let's signal reconnect event - if(self.replset._commandsStore.count() > 0) { - self.replset.emit('reconnect'); - } - - // Execute any waiting reads - self.replset._commandsStore.execute_queries(); - } else { - _server.close(); - } - - // Set any tags on the instance server - _server.name = doc.me; - _server.tags = doc.tags; - // Process the next server - setTimeout(function() { - _reconnect_servers(self, reconnect_servers); - }, self.options.haInterval); - }); - } else { - _server.close(); - self.replset.__executeAllServerSpecificErrorCallbacks(_server.socketOptions.host, _server.socketOptions.port, err); - - setTimeout(function() { - _reconnect_servers(self, reconnect_servers); - }, self.options.haInterval); - } - }); -} - -var _apply_auths = function(self, _db, _server, _callback) { - if(self.replset.auth.length() == 0) return _callback(null); - // Apply any authentication needed - if(self.replset.auth.length() > 0) { - var pending = self.replset.auth.length(); - var connections = _server.allRawConnections(); - var pendingAuthConn = connections.length; - // Connection function - var connectionFunction = function(auth, _connection, __callback) { - var pending = auth.length(); - - for(var j = 0; j < pending; j++) { - // Get the auth object - var _auth = auth.get(j); - // Unpack the parameter - var username = _auth.username; - var password = _auth.password; - var options = { - authMechanism: _auth.authMechanism - , authSource: _auth.authdb - , connection: _connection - }; - - // If we have changed the service name - if(_auth.gssapiServiceName) - options.gssapiServiceName = _auth.gssapiServiceName; - - // Hold any error - var _error = null; - - // Authenticate against the credentials - _db.authenticate(username, password, options, function(err, result) { - _error = err != null ? err : _error; - // Adjust the pending authentication - pending = pending - 1; - // Finished up - if(pending == 0) __callback(_error ? _error : null, _error ? false : true); - }); - } - } - - // Final error object - var finalError = null; - // Iterate over all the connections - for(var i = 0; i < connections.length; i++) { - connectionFunction(self.replset.auth, connections[i], function(err, result) { - // Pending authentication - pendingAuthConn = pendingAuthConn - 1 ; - - // Save error if any - finalError = err ? err : finalError; - - // If we are done let's finish up - if(pendingAuthConn == 0) { - _callback(null); - } - }); - } - } -} - -var _handle = function(self, server) { - return function(err) { - server.close(); - } -} - -var _repl_set_handler = function(event, self, server) { - var ReplSet = require('./repl_set').ReplSet; - - return function(err, doc) { - server.close(); - - // The event happened to a primary - // Remove it from play - if(self._state.isPrimary(server)) { - self._state.master == null; - self._serverState = ReplSet.REPLSET_READ_ONLY; - } else if(self._state.isSecondary(server)) { - delete self._state.secondaries[server.name]; - } - - // Unpack variables - var host = server.socketOptions.host; - var port = server.socketOptions.port; - - // Fire error on any unknown callbacks - self.__executeAllServerSpecificErrorCallbacks(host, port, err); - } -} - -exports.HighAvailabilityProcess = HighAvailabilityProcess; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js deleted file mode 100755 index 8b3d72b7..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js +++ /dev/null @@ -1,126 +0,0 @@ -var PingStrategy = require('./strategies/ping_strategy').PingStrategy - , StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy - , ReadPreference = require('../read_preference').ReadPreference; - -var Options = function(options) { - options = options || {}; - this._options = options; - this.ha = options.ha || true; - this.haInterval = options.haInterval || 2000; - this.reconnectWait = options.reconnectWait || 1000; - this.retries = options.retries || 30; - this.rs_name = options.rs_name; - this.socketOptions = options.socketOptions || {}; - this.readPreference = options.readPreference; - this.readSecondary = options.read_secondary; - this.poolSize = options.poolSize == null ? 5 : options.poolSize; - this.strategy = options.strategy || 'ping'; - this.secondaryAcceptableLatencyMS = options.secondaryAcceptableLatencyMS || 15; - this.connectArbiter = options.connectArbiter || false; - this.connectWithNoPrimary = options.connectWithNoPrimary || false; - this.logger = options.logger; - this.ssl = options.ssl || false; - this.sslValidate = options.sslValidate || false; - this.sslCA = options.sslCA; - this.sslCert = options.sslCert; - this.sslKey = options.sslKey; - this.sslPass = options.sslPass; - this.emitOpen = options.emitOpen || true; -} - -Options.prototype.init = function() { - if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) { - throw new Error("The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate"); - } - - // Make sure strategy is one of the two allowed - if(this.strategy != null && (this.strategy != 'ping' && this.strategy != 'statistical' && this.strategy != 'none')) - throw new Error("Only ping or statistical strategies allowed"); - - if(this.strategy == null) this.strategy = 'ping'; - - // Set logger if strategy exists - if(this.strategyInstance) this.strategyInstance.logger = this.logger; - - // Unpack read Preference - var readPreference = this.readPreference; - // Validate correctness of Read preferences - if(readPreference != null) { - if(readPreference != ReadPreference.PRIMARY && readPreference != ReadPreference.PRIMARY_PREFERRED - && readPreference != ReadPreference.SECONDARY && readPreference != ReadPreference.SECONDARY_PREFERRED - && readPreference != ReadPreference.NEAREST && typeof readPreference != 'object' && readPreference['_type'] != 'ReadPreference') { - throw new Error("Illegal readPreference mode specified, " + JSON.stringify(readPreference)); - } - - this.readPreference = readPreference; - } else { - this.readPreference = null; - } - - // Ensure read_secondary is set correctly - if(this.readSecondary != null) - this.readSecondary = this.readPreference == ReadPreference.PRIMARY - || this.readPreference == false - || this.readPreference == null ? false : true; - - // Ensure correct slave set - if(this.readSecondary) this.slaveOk = true; - - // Set up logger if any set - this.logger = this.logger != null - && (typeof this.logger.debug == 'function') - && (typeof this.logger.error == 'function') - && (typeof this.logger.debug == 'function') - ? this.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}; - - // Connection timeout - this.connectTimeoutMS = typeof this.socketOptions.connectTimeoutMS == 'number' - ? this.socketOptions.connectTimeoutMS - : 1000; - - // Socket connection timeout - this.socketTimeoutMS = typeof this.socketOptions.socketTimeoutMS == 'number' - ? this.socketOptions.socketTimeoutMS - : 30000; -} - -Options.prototype.decorateAndClean = function(servers, callBackStore) { - var self = this; - - // var de duplicate list - var uniqueServers = {}; - // De-duplicate any servers in the seed list - for(var i = 0; i < servers.length; i++) { - var server = servers[i]; - // If server does not exist set it - if(uniqueServers[server.host + ":" + server.port] == null) { - uniqueServers[server.host + ":" + server.port] = server; - } - } - - // Let's set the deduplicated list of servers - var finalServers = []; - // Add the servers - for(var key in uniqueServers) { - finalServers.push(uniqueServers[key]); - } - - finalServers.forEach(function(server) { - // Ensure no server has reconnect on - server.options.auto_reconnect = false; - // Set up ssl options - server.ssl = self.ssl; - server.sslValidate = self.sslValidate; - server.sslCA = self.sslCA; - server.sslCert = self.sslCert; - server.sslKey = self.sslKey; - server.sslPass = self.sslPass; - server.poolSize = self.poolSize; - // Set callback store - server._callBackStore = callBackStore; - }); - - return finalServers; -} - -exports.Options = Options; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js deleted file mode 100755 index 2c0b8df3..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js +++ /dev/null @@ -1,839 +0,0 @@ -var ReadPreference = require('../read_preference').ReadPreference - , DbCommand = require('../../commands/db_command').DbCommand - , inherits = require('util').inherits - , format = require('util').format - , timers = require('timers') - , Server = require('../server').Server - , utils = require('../../utils') - , PingStrategy = require('./strategies/ping_strategy').PingStrategy - , StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy - , Options = require('./options').Options - , ServerCapabilities = require('../server_capabilities').ServerCapabilities - , ReplSetState = require('./repl_set_state').ReplSetState - , HighAvailabilityProcess = require('./ha').HighAvailabilityProcess - , Base = require('../base').Base; - -var STATE_STARTING_PHASE_1 = 0; -var STATE_PRIMARY = 1; -var STATE_SECONDARY = 2; -var STATE_RECOVERING = 3; -var STATE_FATAL_ERROR = 4; -var STATE_STARTING_PHASE_2 = 5; -var STATE_UNKNOWN = 6; -var STATE_ARBITER = 7; -var STATE_DOWN = 8; -var STATE_ROLLBACK = 9; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../../utils').processor(); - -/** - * ReplSet constructor provides replicaset functionality - * - * Options - * - **ha** {Boolean, default:true}, turn on high availability. - * - **haInterval** {Number, default:2000}, time between each replicaset status check. - * - **reconnectWait** {Number, default:1000}, time to wait in miliseconds before attempting reconnect. - * - **retries** {Number, default:30}, number of times to attempt a replicaset reconnect. - * - **rs_name** {String}, the name of the replicaset to connect to. - * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number)) - * - **strategy** {String, default:'ping'}, selection strategy for reads choose between (ping, statistical and none, default is ping) - * - **secondaryAcceptableLatencyMS** {Number, default:15}, sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) - * - **connectWithNoPrimary** {Boolean, default:false}, sets if the driver should connect even if no primary is available - * - **connectArbiter** {Boolean, default:false}, sets if the driver should connect to arbiters or not. - * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**. - * - **poolSize** {Number, default:5}, number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support) - * - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * - * @class Represents a - Replicaset Configuration - * @param {Array} list of server objects participating in the replicaset. - * @param {Object} [options] additional options for the replicaset connection. - */ -var ReplSet = exports.ReplSet = function(servers, options) { - // Set up basic - if(!(this instanceof ReplSet)) - return new ReplSet(servers, options); - - // Set up event emitter - Base.call(this); - - // Ensure we have a list of servers - if(!Array.isArray(servers)) throw Error("The parameter must be an array of servers and contain at least one server"); - // Ensure no Mongos's - for(var i = 0; i < servers.length; i++) { - if(!(servers[i] instanceof Server)) throw new Error("list of servers must be of type Server"); - } - - // Save the options - this.options = new Options(options); - // Ensure basic validation of options - this.options.init(); - - // Server state - this._serverState = ReplSet.REPLSET_DISCONNECTED; - // Add high availability process - this._haProcess = new HighAvailabilityProcess(this, this.options); - - // Let's iterate over all the provided server objects and decorate them - this.servers = this.options.decorateAndClean(servers, this._callBackStore); - // Throw error if no seed servers - if(this.servers.length == 0) throw new Error("No valid seed servers in the array"); - - // Let's set up our strategy object for picking secondaries - if(this.options.strategy == 'ping') { - // Create a new instance - this.strategyInstance = new PingStrategy(this, this.options.secondaryAcceptableLatencyMS); - } else if(this.options.strategy == 'statistical') { - // Set strategy as statistical - this.strategyInstance = new StatisticsStrategy(this); - // Add enable query information - this.enableRecordQueryStats(true); - } - - this.emitOpen = this.options.emitOpen || true; - // Set up a clean state - this._state = new ReplSetState(this); - // Current round robin selected server - this._currentServerChoice = 0; - // Ensure up the server callbacks - for(var i = 0; i < this.servers.length; i++) { - this.servers[i]._callBackStore = this._callBackStore; - this.servers[i].name = format("%s:%s", this.servers[i].host, this.servers[i].port) - this.servers[i].replicasetInstance = this; - this.servers[i].options.auto_reconnect = false; - this.servers[i].poolSize = this.options.poolSize; - this.servers[i].inheritReplSetOptionsFrom(this); - } - - // Allow setting the socketTimeoutMS on all connections - // to work around issues such as secondaries blocking due to compaction - utils.setSocketTimeoutProperty(this, this.options.socketOptions); -} - -/** - * @ignore - */ -inherits(ReplSet, Base); - -// Replicaset states -ReplSet.REPLSET_CONNECTING = 'connecting'; -ReplSet.REPLSET_DISCONNECTED = 'disconnected'; -ReplSet.REPLSET_CONNECTED = 'connected'; -ReplSet.REPLSET_RECONNECTING = 'reconnecting'; -ReplSet.REPLSET_DESTROYED = 'destroyed'; -ReplSet.REPLSET_READ_ONLY = 'readonly'; - -ReplSet.prototype.isAutoReconnect = function() { - return true; -} - -ReplSet.prototype.canWrite = function() { - return this._state.master && this._state.master.isConnected(); -} - -ReplSet.prototype.canRead = function(read) { - if((read == ReadPreference.PRIMARY - || (typeof read == 'object' && read.mode == ReadPreference.PRIMARY) - || read == null || read == false) && (this._state.master == null || !this._state.master.isConnected())) return false; - return Object.keys(this._state.secondaries).length > 0; -} - -/** - * @ignore - */ -ReplSet.prototype.enableRecordQueryStats = function(enable) { - // Set the global enable record query stats - this.recordQueryStats = enable; - - // Enable all the servers - for(var i = 0; i < this.servers.length; i++) { - this.servers[i].enableRecordQueryStats(enable); - } -} - -/** - * @ignore - */ -ReplSet.prototype.setSocketOptions = function(options) { - var servers = this.allServerInstances(); - - if(typeof options.socketTimeoutMS == 'number') { - this.options.socketOptions.socketTimeoutMS = options.socketTimeoutMS; - } - - if(typeof options.connectTimeoutMS == 'number') - this.options.socketOptions.connectTimeoutMS = options.connectTimeoutMS; - - for(var i = 0; i < servers.length; i++) { - servers[i].setSocketOptions(options); - } -} - -/** - * @ignore - */ -ReplSet.prototype.setReadPreference = function(preference) { - this.options.readPreference = preference; -} - -ReplSet.prototype.connect = function(parent, options, callback) { - if(this._serverState != ReplSet.REPLSET_DISCONNECTED) - return callback(new Error("in process of connection")); - - // If no callback throw - if(!(typeof callback == 'function')) - throw new Error("cannot call ReplSet.prototype.connect with no callback function"); - - var self = this; - // Save db reference - this.options.db = parent; - // Set replicaset as connecting - this._serverState = ReplSet.REPLSET_CONNECTING - // Copy all the servers to our list of seeds - var candidateServers = this.servers.slice(0); - // Pop the first server - var server = candidateServers.pop(); - server.name = format("%s:%s", server.host, server.port); - // Set up the options - var opts = { - returnIsMasterResults: true, - eventReceiver: server - } - - // Register some event listeners - this.once("fullsetup", function(err, db, replset) { - // Set state to connected - self._serverState = ReplSet.REPLSET_CONNECTED; - // Stop any process running - if(self._haProcess) self._haProcess.stop(); - // Start the HA process - self._haProcess.start(); - - // Emit fullsetup - processor(function() { - if(self.emitOpen) - self._emitAcrossAllDbInstances(self, null, "open", null, null, null); - - self._emitAcrossAllDbInstances(self, null, "fullsetup", null, null, null); - }); - - // If we have a strategy defined start it - if(self.strategyInstance) { - self.strategyInstance.start(); - } - - // Finishing up the call - callback(err, db, replset); - }); - - // Errors - this.once("connectionError", function(err, result) { - callback(err, result); - }); - - // Attempt to connect to the server - server.connect(this.options.db, opts, _connectHandler(this, candidateServers, server)); -} - -ReplSet.prototype.close = function(callback) { - var self = this; - // Set as destroyed - this._serverState = ReplSet.REPLSET_DESTROYED; - // Stop the ha - this._haProcess.stop(); - - // If we have a strategy stop it - if(this.strategyInstance) { - this.strategyInstance.stop(); - } - - // Kill all servers available - for(var name in this._state.addresses) { - this._state.addresses[name].close(); - } - - // Clean out the state - this._state = new ReplSetState(this); - - // Emit close event - processor(function() { - self._emitAcrossAllDbInstances(self, null, "close", null, null, true) - }); - - // Flush out any remaining call handlers - self._flushAllCallHandlers(utils.toError("Connection Closed By Application")); - - // Callback - if(typeof callback == 'function') - return callback(null, null); -} - -/** - * Creates a new server for the `replset` based on `host`. - * - * @param {String} host - host:port pair (localhost:27017) - * @param {ReplSet} replset - the ReplSet instance - * @return {Server} - * @ignore - */ -var createServer = function(self, host, options) { - // copy existing socket options to new server - var socketOptions = {} - if(options.socketOptions) { - var keys = Object.keys(options.socketOptions); - for(var k = 0; k < keys.length; k++) { - socketOptions[keys[k]] = options.socketOptions[keys[k]]; - } - } - - var parts = host.split(/:/); - if(1 === parts.length) { - parts[1] = Connection.DEFAULT_PORT; - } - - socketOptions.host = parts[0]; - socketOptions.port = parseInt(parts[1], 10); - - var serverOptions = { - readPreference: options.readPreference, - socketOptions: socketOptions, - poolSize: options.poolSize, - logger: options.logger, - auto_reconnect: false, - ssl: options.ssl, - sslValidate: options.sslValidate, - sslCA: options.sslCA, - sslCert: options.sslCert, - sslKey: options.sslKey, - sslPass: options.sslPass - } - - var server = new Server(socketOptions.host, socketOptions.port, serverOptions); - // Set up shared state - server._callBackStore = self._callBackStore; - server.replicasetInstance = self; - server.enableRecordQueryStats(self.recordQueryStats); - // Set up event handlers - server.on("close", _handler("close", self, server)); - server.on("error", _handler("error", self, server)); - server.on("timeout", _handler("timeout", self, server)); - return server; -} - -var _handler = function(event, self, server) { - return function(err, doc) { - // The event happened to a primary - // Remove it from play - if(self._state.isPrimary(server)) { - // Emit that the primary left the replicaset - self.emit('left', 'primary', server); - // Get the current master - var current_master = self._state.master; - self._state.master = null; - self._serverState = ReplSet.REPLSET_READ_ONLY; - - if(current_master != null) { - // Unpack variables - var host = current_master.socketOptions.host; - var port = current_master.socketOptions.port; - - // Fire error on any unknown callbacks - self.__executeAllServerSpecificErrorCallbacks(host, port, err); - } - } else if(self._state.isSecondary(server)) { - // Emit that a secondary left the replicaset - self.emit('left', 'secondary', server); - // Delete from the list - delete self._state.secondaries[server.name]; - } - - // If there is no more connections left and the setting is not destroyed - // set to disconnected - if(Object.keys(self._state.addresses).length == 0 - && self._serverState != ReplSet.REPLSET_DESTROYED) { - self._serverState = ReplSet.REPLSET_DISCONNECTED; - - // Emit close across all the attached db instances - self._dbStore.emit("close", new Error("replicaset disconnected, no valid servers contactable over tcp"), null, true); - } - - // Unpack variables - var host = server.socketOptions.host; - var port = server.socketOptions.port; - - // Fire error on any unknown callbacks - self.__executeAllServerSpecificErrorCallbacks(host, port, err); - } -} - -var locateNewServers = function(self, state, candidateServers, ismaster) { - // Retrieve the host - var hosts = ismaster.hosts; - // In candidate servers - var inCandidateServers = function(name, candidateServers) { - for(var i = 0; i < candidateServers.length; i++) { - if(candidateServers[i].name == name) return true; - } - - return false; - } - - // New servers - var newServers = []; - if(Array.isArray(hosts)) { - // Let's go over all the hosts - for(var i = 0; i < hosts.length; i++) { - if(!state.contains(hosts[i]) - && !inCandidateServers(hosts[i], candidateServers)) { - newServers.push(createServer(self, hosts[i], self.options)); - } - } - } - - // Return list of possible new servers - return newServers; -} - -var _connectHandler = function(self, candidateServers, instanceServer) { - return function(err, doc) { - // If we have an error add to the list - if(err) { - self._state.errors[instanceServer.name] = instanceServer; - } else { - delete self._state.errors[instanceServer.name]; - } - - if(!err) { - var ismaster = doc.documents[0] - - // Error the server if - if(!ismaster.ismaster - && !ismaster.secondary) { - self._state.errors[instanceServer.name] = instanceServer; - } - - // Set server capabilities - instanceServer.serverCapabilities = new ServerCapabilities(ismaster); - - // Set server capabilities on all the connections - var connections = instanceServer.allRawConnections(); - for(var i = 0; i < connections.length; i++) { - connections[i].serverCapabilities = instanceServer.serverCapabilities; - } - } - - // No error let's analyse the ismaster command - if(!err && self._state.errors[instanceServer.name] == null) { - var ismaster = doc.documents[0] - - // If no replicaset name exists set the current one - if(self.options.rs_name == null) { - self.options.rs_name = ismaster.setName; - } - - // If we have a member that is not part of the set let's finish up - if(typeof ismaster.setName == 'string' && ismaster.setName != self.options.rs_name) { - return self.emit("connectionError", new Error("Replicaset name " + ismaster.setName + " does not match specified name " + self.options.rs_name)); - } - - // Add the error handlers - instanceServer.on("close", _handler("close", self, instanceServer)); - instanceServer.on("error", _handler("error", self, instanceServer)); - instanceServer.on("timeout", _handler("timeout", self, instanceServer)); - - // Set any tags on the instance server - instanceServer.name = ismaster.me; - instanceServer.tags = ismaster.tags; - - // Add the server to the list - self._state.addServer(instanceServer, ismaster); - - // Check if we have more servers to add (only check when done with initial set) - if(candidateServers.length == 0) { - // Get additional new servers that are not currently in set - var new_servers = locateNewServers(self, self._state, candidateServers, ismaster); - - // Locate any new servers that have not errored out yet - for(var i = 0; i < new_servers.length; i++) { - if(self._state.errors[new_servers[i].name] == null) { - candidateServers.push(new_servers[i]) - } - } - } - } - - // If the candidate server list is empty and no valid servers - if(candidateServers.length == 0 && - !self._state.hasValidServers()) { - return self.emit("connectionError", new Error("No valid replicaset instance servers found")); - } else if(candidateServers.length == 0) { - if(!self.options.connectWithNoPrimary && (self._state.master == null || !self._state.master.isConnected())) { - return self.emit("connectionError", new Error("No primary found in set")); - } - return self.emit("fullsetup", null, self.options.db, self); - } - - // Let's connect the next server - var nextServer = candidateServers.pop(); - - // Set up the options - var opts = { - returnIsMasterResults: true, - eventReceiver: nextServer - } - - // Attempt to connect to the server - nextServer.connect(self.options.db, opts, _connectHandler(self, candidateServers, nextServer)); - } -} - -ReplSet.prototype.isDestroyed = function() { - return this._serverState == ReplSet.REPLSET_DESTROYED; -} - -ReplSet.prototype.isConnected = function(read) { - var isConnected = false; - - if(read == null || read == ReadPreference.PRIMARY || read == false) - isConnected = this._state.master != null && this._state.master.isConnected(); - - if((read == ReadPreference.PRIMARY_PREFERRED || read == ReadPreference.SECONDARY_PREFERRED || read == ReadPreference.NEAREST) - && ((this._state.master != null && this._state.master.isConnected()) - || (this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0))) { - isConnected = true; - } else if(read == ReadPreference.SECONDARY) { - isConnected = this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0; - } - - // No valid connection return false - return isConnected; -} - -ReplSet.prototype.isMongos = function() { - return false; -} - -ReplSet.prototype.checkoutWriter = function() { - if(this._state.master) return this._state.master.checkoutWriter(); - return new Error("no writer connection available"); -} - -ReplSet.prototype.processIsMaster = function(_server, _ismaster) { - // Server in recovery mode, remove it from available servers - if(!_ismaster.ismaster && !_ismaster.secondary) { - // Locate the actual server - var server = this._state.addresses[_server.name]; - // Close the server, simulating the closing of the connection - // to get right removal semantics - if(server) server.close(); - // Execute any callback errors - _handler(null, this, server)(new Error("server is in recovery mode")); - } -} - -ReplSet.prototype.allRawConnections = function() { - var connections = []; - - for(var name in this._state.addresses) { - connections = connections.concat(this._state.addresses[name].allRawConnections()); - } - - return connections; -} - -/** - * @ignore - */ -ReplSet.prototype.allServerInstances = function() { - var self = this; - // If no state yet return empty - if(!self._state) return []; - // Close all the servers (concatenate entire list of servers first for ease) - var allServers = self._state.master != null ? [self._state.master] : []; - - // Secondary keys - var keys = Object.keys(self._state.secondaries); - // Add all secondaries - for(var i = 0; i < keys.length; i++) { - allServers.push(self._state.secondaries[keys[i]]); - } - - // Return complete list of all servers - return allServers; -} - -/** - * @ignore - */ -ReplSet.prototype.checkoutReader = function(readPreference, tags) { - var connection = null; - - // If we have a read preference object unpack it - if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') { - // Validate if the object is using a valid mode - if(!readPreference.isValid()) throw new Error("Illegal readPreference mode specified, " + JSON.stringify(readPreference.mode)); - // Set the tag - tags = readPreference.tags; - readPreference = readPreference.mode; - } else if(typeof readPreference == 'object' && readPreference['_type'] != 'ReadPreference') { - return new Error("read preferences must be either a string or an instance of ReadPreference"); - } - - // Set up our read Preference, allowing us to override the readPreference - var finalReadPreference = readPreference != null ? readPreference : this.options.readPreference; - - // Ensure we unpack a reference - if(finalReadPreference != null && typeof finalReadPreference == 'object' && finalReadPreference['_type'] == 'ReadPreference') { - // Validate if the object is using a valid mode - if(!finalReadPreference.isValid()) throw new Error("Illegal readPreference mode specified, " + JSON.stringify(finalReadPreference.mode)); - // Set the tag - tags = finalReadPreference.tags; - readPreference = finalReadPreference.mode; - } - - // Finalize the read preference setup - finalReadPreference = finalReadPreference == true ? ReadPreference.SECONDARY_PREFERRED : finalReadPreference; - finalReadPreference = finalReadPreference == null ? ReadPreference.PRIMARY : finalReadPreference; - - // If we are reading from a primary - if(finalReadPreference == 'primary') { - // If we provide a tags set send an error - if(typeof tags == 'object' && tags != null) { - return new Error("PRIMARY cannot be combined with tags"); - } - - // If we provide a tags set send an error - if(this._state.master == null) { - return new Error("No replica set primary available for query with ReadPreference PRIMARY"); - } - - // Checkout a writer - return this.checkoutWriter(); - } - - // If we have specified to read from a secondary server grab a random one and read - // from it, otherwise just pass the primary connection - if((this.options.readSecondary || finalReadPreference == ReadPreference.SECONDARY_PREFERRED || finalReadPreference == ReadPreference.SECONDARY) && Object.keys(this._state.secondaries).length > 0) { - // If we have tags, look for servers matching the specific tag - if(this.strategyInstance != null) { - // Only pick from secondaries - var _secondaries = []; - for(var key in this._state.secondaries) { - _secondaries.push(this._state.secondaries[key]); - } - - if(finalReadPreference == ReadPreference.SECONDARY) { - // Check out the nearest from only the secondaries - connection = this.strategyInstance.checkoutConnection(tags, _secondaries); - } else { - connection = this.strategyInstance.checkoutConnection(tags, _secondaries); - // No candidate servers that match the tags, error - if(connection == null || connection instanceof Error) { - // No secondary server avilable, attemp to checkout a primary server - connection = this.checkoutWriter(); - // If no connection return an error - if(connection == null || connection instanceof Error) { - return new Error("No replica set members available for query"); - } - } - } - } else if(tags != null && typeof tags == 'object') { - // Get connection - connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) { - // No candidate servers that match the tags, error - if(connection == null) { - return new Error("No replica set members available for query"); - } - } else { - connection = _roundRobin(this, tags); - } - } else if(finalReadPreference == ReadPreference.PRIMARY_PREFERRED) { - // Check if there is a primary available and return that if possible - connection = this.checkoutWriter(); - // If no connection available checkout a secondary - if(connection == null || connection instanceof Error) { - // If we have tags, look for servers matching the specific tag - if(tags != null && typeof tags == 'object') { - // Get connection - connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) { - // No candidate servers that match the tags, error - if(connection == null) { - return new Error("No replica set members available for query"); - } - } else { - connection = _roundRobin(this, tags); - } - } - } else if(finalReadPreference == ReadPreference.SECONDARY_PREFERRED) { - // If we have tags, look for servers matching the specific tag - if(this.strategyInstance != null) { - connection = this.strategyInstance.checkoutConnection(tags); - - // No candidate servers that match the tags, error - if(connection == null || connection instanceof Error) { - // No secondary server avilable, attemp to checkout a primary server - connection = this.checkoutWriter(); - // If no connection return an error - if(connection == null || connection instanceof Error) { - var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference; - return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags)); - } - } - } else if(tags != null && typeof tags == 'object') { - // Get connection - connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) { - // No candidate servers that match the tags, error - if(connection == null) { - // No secondary server avilable, attemp to checkout a primary server - connection = this.checkoutWriter(); - // If no connection return an error - if(connection == null || connection instanceof Error) { - var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference; - return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags)); - } - } - } - } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance != null) { - connection = this.strategyInstance.checkoutConnection(tags); - } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance == null) { - return new Error("A strategy for calculating nearness must be enabled such as ping or statistical"); - } else if(finalReadPreference == ReadPreference.SECONDARY && Object.keys(this._state.secondaries).length == 0) { - if(tags != null && typeof tags == 'object') { - var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference; - return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags)); - } else { - return new Error("No replica set secondary available for query with ReadPreference SECONDARY"); - } - } else { - connection = this.checkoutWriter(); - } - - // Return the connection - return connection; -} - -/** - * @ignore - */ -var _pickFromTags = function(self, tags) { - // If we have an array or single tag selection - var tagObjects = Array.isArray(tags) ? tags : [tags]; - // Iterate over all tags until we find a candidate server - for(var _i = 0; _i < tagObjects.length; _i++) { - // Grab a tag object - var tagObject = tagObjects[_i]; - // Matching keys - var matchingKeys = Object.keys(tagObject); - // Match all the servers that match the provdided tags - var keys = Object.keys(self._state.secondaries); - var candidateServers = []; - - for(var i = 0; i < keys.length; i++) { - var server = self._state.secondaries[keys[i]]; - // If we have tags match - if(server.tags != null) { - var matching = true; - // Ensure we have all the values - for(var j = 0; j < matchingKeys.length; j++) { - if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) { - matching = false; - break; - } - } - - // If we have a match add it to the list of matching servers - if(matching) { - candidateServers.push(server); - } - } - } - - // If we have a candidate server return - if(candidateServers.length > 0) { - if(self.strategyInstance) return self.strategyInstance.checkoutConnection(tags, candidateServers); - // Set instance to return - return candidateServers[Math.floor(Math.random() * candidateServers.length)].checkoutReader(); - } - } - - // No connection found - return null; -} - -/** - * Pick a secondary using round robin - * - * @ignore - */ -function _roundRobin (replset, tags) { - var keys = Object.keys(replset._state.secondaries); - // Update index - replset._currentServerChoice = replset._currentServerChoice + 1; - // Pick a server - var key = keys[replset._currentServerChoice % keys.length]; - - var conn = null != replset._state.secondaries[key] - ? replset._state.secondaries[key].checkoutReader() - : null; - - // If connection is null fallback to first available secondary - if(null == conn) { - conn = pickFirstConnectedSecondary(replset, tags); - } - - return conn; -} - -/** - * @ignore - */ -var pickFirstConnectedSecondary = function pickFirstConnectedSecondary(self, tags) { - var keys = Object.keys(self._state.secondaries); - var connection; - - // Find first available reader if any - for(var i = 0; i < keys.length; i++) { - connection = self._state.secondaries[keys[i]].checkoutReader(); - if(connection) return connection; - } - - // If we still have a null, read from primary if it's not secondary only - if(self._readPreference == ReadPreference.SECONDARY_PREFERRED) { - connection = self._state.master.checkoutReader(); - if(connection) return connection; - } - - var preferenceName = self._readPreference == ReadPreference.SECONDARY_PREFERRED - ? 'secondary' - : self._readPreference; - - return new Error("No replica set member available for query with ReadPreference " - + preferenceName + " and tags " + JSON.stringify(tags)); -} - -/** - * Get list of secondaries - * @ignore - */ -Object.defineProperty(ReplSet.prototype, "secondaries", {enumerable: true - , get: function() { - return utils.objectToArray(this._state.secondaries); - } -}); - -/** - * Get list of secondaries - * @ignore - */ -Object.defineProperty(ReplSet.prototype, "arbiters", {enumerable: true - , get: function() { - return utils.objectToArray(this._state.arbiters); - } -}); - diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js deleted file mode 100755 index 1fbd9c0c..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Interval state object constructor - * - * @ignore - */ -var ReplSetState = function ReplSetState (replset) { - this.errorMessages = []; - this.secondaries = {}; - this.addresses = {}; - this.arbiters = {}; - this.passives = {}; - this.members = []; - this.errors = {}; - this.setName = null; - this.master = null; - this.replset = replset; -} - -ReplSetState.prototype.hasValidServers = function() { - var validServers = []; - if(this.master && this.master.isConnected()) return true; - - if(this.secondaries) { - var keys = Object.keys(this.secondaries) - for(var i = 0; i < keys.length; i++) { - if(this.secondaries[keys[i]].isConnected()) - return true; - } - } - - return false; -} - -ReplSetState.prototype.getAllReadServers = function() { - var candidate_servers = []; - for(var name in this.addresses) { - candidate_servers.push(this.addresses[name]); - } - - // Return all possible read candidates - return candidate_servers; -} - -ReplSetState.prototype.addServer = function(server, master) { - server.name = master.me; - - if(master.ismaster) { - this.master = server; - this.addresses[server.name] = server; - this.replset.emit('joined', "primary", master, server); - } else if(master.secondary) { - this.secondaries[server.name] = server; - this.addresses[server.name] = server; - this.replset.emit('joined', "secondary", master, server); - } else if(master.arbiters) { - this.arbiters[server.name] = server; - this.addresses[server.name] = server; - this.replset.emit('joined', "arbiter", master, server); - } -} - -ReplSetState.prototype.contains = function(host) { - return this.addresses[host] != null; -} - -ReplSetState.prototype.isPrimary = function(server) { - return this.master && this.master.name == server.name; -} - -ReplSetState.prototype.isSecondary = function(server) { - return this.secondaries[server.name] != null; -} - -exports.ReplSetState = ReplSetState; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js deleted file mode 100755 index 7e2a6c9a..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js +++ /dev/null @@ -1,366 +0,0 @@ -var Server = require("../../server").Server - , format = require('util').format; - -// The ping strategy uses pings each server and records the -// elapsed time for the server so it can pick a server based on lowest -// return time for the db command {ping:true} -var PingStrategy = exports.PingStrategy = function(replicaset, secondaryAcceptableLatencyMS) { - this.replicaset = replicaset; - this.secondaryAcceptableLatencyMS = secondaryAcceptableLatencyMS; - this.state = 'disconnected'; - // Interval of ping attempts - this.pingInterval = replicaset.options.socketOptions.pingInterval || 5000; - // Timeout for ping response, default - no timeout - this.pingTimeout = replicaset.options.socketOptions.pingTimeout || null; - // Class instance - this.Db = require("../../../db").Db; - // Active db connections - this.dbs = {}; - // Current server index - this.index = 0; - // Logger api - this.Logger = null; -} - -// Starts any needed code -PingStrategy.prototype.start = function(callback) { - // already running? - if ('connected' == this.state) return; - - this.state = 'connected'; - - // Start ping server - this._pingServer(callback); -} - -// Stops and kills any processes running -PingStrategy.prototype.stop = function(callback) { - // Stop the ping process - this.state = 'disconnected'; - - // Stop all the server instances - for(var key in this.dbs) { - this.dbs[key].close(); - } - - // optional callback - callback && callback(null, null); -} - -PingStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) { - // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS - // Create a list of candidat servers, containing the primary if available - var candidateServers = []; - var self = this; - - // If we have not provided a list of candidate servers use the default setup - if(!Array.isArray(secondaryCandidates)) { - candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : []; - // Add all the secondaries - var keys = Object.keys(this.replicaset._state.secondaries); - for(var i = 0; i < keys.length; i++) { - candidateServers.push(this.replicaset._state.secondaries[keys[i]]) - } - } else { - candidateServers = secondaryCandidates; - } - - // Final list of eligable server - var finalCandidates = []; - - // If we have tags filter by tags - if(tags != null && typeof tags == 'object') { - // If we have an array or single tag selection - var tagObjects = Array.isArray(tags) ? tags : [tags]; - // Iterate over all tags until we find a candidate server - for(var _i = 0; _i < tagObjects.length; _i++) { - // Grab a tag object - var tagObject = tagObjects[_i]; - // Matching keys - var matchingKeys = Object.keys(tagObject); - // Remove any that are not tagged correctly - for(var i = 0; i < candidateServers.length; i++) { - var server = candidateServers[i]; - // If we have tags match - if(server.tags != null) { - var matching = true; - - // Ensure we have all the values - for(var j = 0; j < matchingKeys.length; j++) { - if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) { - matching = false; - break; - } - } - - // If we have a match add it to the list of matching servers - if(matching) { - finalCandidates.push(server); - } - } - } - } - } else { - // Final array candidates - var finalCandidates = candidateServers; - } - - // Filter out any non-connected servers - finalCandidates = finalCandidates.filter(function(s) { - return s.isConnected(); - }) - - // Sort by ping time - finalCandidates.sort(function(a, b) { - return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs']; - }); - - if(0 === finalCandidates.length) - return new Error("No replica set members available for query"); - - // find lowest server with a ping time - var lowest = finalCandidates.filter(function (server) { - return undefined != server.runtimeStats.pingMs; - })[0]; - - if(!lowest) { - lowest = finalCandidates[0]; - } - - // convert to integer - var lowestPing = lowest.runtimeStats.pingMs | 0; - - // determine acceptable latency - var acceptable = lowestPing + this.secondaryAcceptableLatencyMS; - - // remove any server responding slower than acceptable - var len = finalCandidates.length; - while(len--) { - if(finalCandidates[len].runtimeStats['pingMs'] > acceptable) { - finalCandidates.splice(len, 1); - } - } - - if(self.logger && self.logger.debug) { - self.logger.debug("Ping strategy selection order for tags", tags); - finalCandidates.forEach(function(c) { - self.logger.debug(format("%s:%s = %s ms", c.host, c.port, c.runtimeStats['pingMs']), null); - }) - } - - // If no candidates available return an error - if(finalCandidates.length == 0) - return new Error("No replica set members available for query"); - - // Ensure no we don't overflow - this.index = this.index % finalCandidates.length - // Pick a random acceptable server - var connection = finalCandidates[this.index].checkoutReader(); - // Point to next candidate (round robin style) - this.index = this.index + 1; - - if(self.logger && self.logger.debug) { - if(connection) - self.logger.debug(format("picked server %s:%s", connection.socketOptions.host, connection.socketOptions.port)); - } - - return connection; -} - -PingStrategy.prototype._pingServer = function(callback) { - var self = this; - - // Ping server function - var pingFunction = function() { - // Our state changed to disconnected or destroyed return - if(self.state == 'disconnected' || self.state == 'destroyed') return; - // If the replicaset is destroyed return - if(self.replicaset.isDestroyed() || self.replicaset._serverState == 'disconnected') return - - // Create a list of all servers we can send the ismaster command to - var allServers = self.replicaset._state.master != null ? [self.replicaset._state.master] : []; - - // Secondary keys - var keys = Object.keys(self.replicaset._state.secondaries); - // Add all secondaries - for(var i = 0; i < keys.length; i++) { - allServers.push(self.replicaset._state.secondaries[keys[i]]); - } - - // Number of server entries - var numberOfEntries = allServers.length; - - // We got keys - for(var i = 0; i < allServers.length; i++) { - - // We got a server instance - var server = allServers[i]; - - // Create a new server object, avoid using internal connections as they might - // be in an illegal state - new function(serverInstance) { - var _db = self.dbs[serverInstance.host + ":" + serverInstance.port]; - // If we have a db - if(_db != null) { - // Startup time of the command - var startTime = Date.now(); - - // Execute ping command in own scope - var _ping = function(__db, __serverInstance) { - - // Server unavailable. Checks only if pingTimeout defined & greater than 0 - var _failTimer = self.pingTimeout ? setTimeout(function () { - if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) { - __serverInstance.close(); - } - }, self.pingTimeout) : null; - - // Execute ping on this connection - __db.executeDbCommand({ping:1}, {failFast:true}, function(err) { - - // Server available - clearTimeout(_failTimer); - - // Emit the ping - self.replicaset.emit("ping", err, serverInstance); - - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) { - __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime; - } - - __db.executeDbCommand({ismaster:1}, {failFast:true}, function(err, result) { - // Emit the ping - self.replicaset.emit("ping_ismaster", err, result, serverInstance); - - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - // Process the ismaster for the server - if(result && result.documents && self.replicaset.processIsMaster) { - self.replicaset.processIsMaster(__serverInstance, result.documents[0]); - } - - // Done with the pinging - done(); - }); - }); - }; - // Ping - _ping(_db, serverInstance); - } else { - var connectTimeoutMS = self.replicaset.options.socketOptions - ? self.replicaset.options.socketOptions.connectTimeoutMS : 0 - - // Create a new master connection - var _server = new Server(serverInstance.host, serverInstance.port, { - auto_reconnect: false, - returnIsMasterResults: true, - slaveOk: true, - poolSize: 1, - socketOptions: { connectTimeoutMS: connectTimeoutMS }, - ssl: self.replicaset.options.ssl, - sslValidate: self.replicaset.options.sslValidate, - sslCA: self.replicaset.options.sslCA, - sslCert: self.replicaset.options.sslCert, - sslKey: self.replicaset.options.sslKey, - sslPass: self.replicaset.options.sslPass - }); - - // Create Db instance - var _db = new self.Db('local', _server, { safe: true }); - _db.on("close", function() { - delete self.dbs[this.serverConfig.host + ":" + this.serverConfig.port]; - }) - - var _ping = function(__db, __serverInstance) { - if(self.state == 'disconnected') { - self.stop(); - return; - } - - __db.open(function(err, db) { - // Emit ping connect - self.replicaset.emit("ping_connect", err, __serverInstance); - - if(self.state == 'disconnected' && __db != null) { - return __db.close(); - } - - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - // Save instance - self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port] = __db; - - // Startup time of the command - var startTime = Date.now(); - - // Execute ping on this connection - __db.executeDbCommand({ping:1}, {failFast:true}, function(err) { - self.replicaset.emit("ping", err, __serverInstance); - - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) { - __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime; - } - - __db.executeDbCommand({ismaster:1}, {failFast:true}, function(err, result) { - self.replicaset.emit("ping_ismaster", err, result, __serverInstance); - - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - // Process the ismaster for the server - if(result && result.documents && self.replicaset.processIsMaster) { - self.replicaset.processIsMaster(__serverInstance, result.documents[0]); - } - - // Done with the pinging - done(); - }); - }); - }); - }; - - // Ping the server - _ping(_db, serverInstance); - } - - function done() { - // Adjust the number of checks - numberOfEntries--; - - // If we are done with all results coming back trigger ping again - if(0 === numberOfEntries && 'connected' == self.state) { - setTimeout(pingFunction, self.pingInterval); - } - } - }(server); - } - } - - // Start pingFunction - pingFunction(); - - callback && callback(null); -} diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js deleted file mode 100755 index 32d23c31..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js +++ /dev/null @@ -1,93 +0,0 @@ -// The Statistics strategy uses the measure of each end-start time for each -// query executed against the db to calculate the mean, variance and standard deviation -// and pick the server which the lowest mean and deviation -var StatisticsStrategy = exports.StatisticsStrategy = function(replicaset) { - this.replicaset = replicaset; - // Logger api - this.Logger = null; -} - -// Starts any needed code -StatisticsStrategy.prototype.start = function(callback) { - callback && callback(null, null); -} - -StatisticsStrategy.prototype.stop = function(callback) { - callback && callback(null, null); -} - -StatisticsStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) { - // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS - // Create a list of candidat servers, containing the primary if available - var candidateServers = []; - - // If we have not provided a list of candidate servers use the default setup - if(!Array.isArray(secondaryCandidates)) { - candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : []; - // Add all the secondaries - var keys = Object.keys(this.replicaset._state.secondaries); - for(var i = 0; i < keys.length; i++) { - candidateServers.push(this.replicaset._state.secondaries[keys[i]]) - } - } else { - candidateServers = secondaryCandidates; - } - - // Final list of eligable server - var finalCandidates = []; - - // If we have tags filter by tags - if(tags != null && typeof tags == 'object') { - // If we have an array or single tag selection - var tagObjects = Array.isArray(tags) ? tags : [tags]; - // Iterate over all tags until we find a candidate server - for(var _i = 0; _i < tagObjects.length; _i++) { - // Grab a tag object - var tagObject = tagObjects[_i]; - // Matching keys - var matchingKeys = Object.keys(tagObject); - // Remove any that are not tagged correctly - for(var i = 0; i < candidateServers.length; i++) { - var server = candidateServers[i]; - // If we have tags match - if(server.tags != null) { - var matching = true; - - // Ensure we have all the values - for(var j = 0; j < matchingKeys.length; j++) { - if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) { - matching = false; - break; - } - } - - // If we have a match add it to the list of matching servers - if(matching) { - finalCandidates.push(server); - } - } - } - } - } else { - // Final array candidates - var finalCandidates = candidateServers; - } - - finalCandidates.sort(function(a, b) { - return a.runtimeStats.queryStats.sScore > b.runtimeStats.queryStats.sScore; - }); - - // If no candidates available return an error - if(finalCandidates.length == 0) return new Error("No replica set members available for query"); - - var bestCandidates = [finalCandidates[0]]; - for (var i = 1; i < finalCandidates.length; ++i) { - if (finalCandidates[i].runtimeStats.queryStats.sScore > finalCandidates[i - 1].runtimeStats.queryStats.sScore) { - break; - } else { - bestCandidates.push(finalCandidates[i]); - } - } - - return bestCandidates[Math.floor(Math.random() * bestCandidates.length)].checkoutReader(); -} diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/server.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/server.js deleted file mode 100755 index e991deb7..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/server.js +++ /dev/null @@ -1,950 +0,0 @@ -var Connection = require('./connection').Connection, - ReadPreference = require('./read_preference').ReadPreference, - DbCommand = require('../commands/db_command').DbCommand, - MongoReply = require('../responses/mongo_reply').MongoReply, - ConnectionPool = require('./connection_pool').ConnectionPool, - EventEmitter = require('events').EventEmitter, - ServerCapabilities = require('./server_capabilities').ServerCapabilities, - Base = require('./base').Base, - format = require('util').format, - utils = require('../utils'), - timers = require('timers'), - inherits = require('util').inherits; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - * Class representing a single MongoDB Server connection - * - * Options - * - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support) - * - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * - **poolSize** {Number, default:5}, number of connections in the connection pool, set to 5 as default for legacy reasons. - * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number)) - * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**. - * - **auto_reconnect** {Boolean, default:false}, reconnect on error. - * - **disableDriverBSONSizeCheck** {Boolean, default:false}, force the server to error if the BSON message is to big - * - * @class Represents a Server connection. - * @param {String} host the server host - * @param {Number} port the server port - * @param {Object} [options] optional options for insert command - */ -function Server(host, port, options) { - // Set up Server instance - if(!(this instanceof Server)) return new Server(host, port, options); - - // Set up event emitter - Base.call(this); - - // Ensure correct values - if(port != null && typeof port == 'object') { - options = port; - port = Connection.DEFAULT_PORT; - } - - var self = this; - this.host = host; - this.port = port; - this.options = options == null ? {} : options; - this.internalConnection; - this.internalMaster = false; - this.connected = false; - this.poolSize = this.options.poolSize == null ? 5 : this.options.poolSize; - this.disableDriverBSONSizeCheck = this.options.disableDriverBSONSizeCheck != null ? this.options.disableDriverBSONSizeCheck : false; - this._used = false; - this.replicasetInstance = null; - - // Emit open setup - this.emitOpen = this.options.emitOpen || true; - // Set ssl as connection method - this.ssl = this.options.ssl == null ? false : this.options.ssl; - // Set ssl validation - this.sslValidate = this.options.sslValidate == null ? false : this.options.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.sslCA = Array.isArray(this.options.sslCA) ? this.options.sslCA : null; - // Certificate to present to the server - this.sslCert = this.options.sslCert; - // Certificate private key if in separate file - this.sslKey = this.options.sslKey; - // Password to unlock private key - this.sslPass = this.options.sslPass; - // Server capabilities - this.serverCapabilities = null; - // Set server name - this.name = format("%s:%s", host, port); - - // Ensure we are not trying to validate with no list of certificates - if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) { - throw new Error("The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate"); - } - - // Contains the isMaster information returned from the server - this.isMasterDoc; - - // Set default connection pool options - this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {}; - if(this.disableDriverBSONSizeCheck) this.socketOptions.disableDriverBSONSizeCheck = this.disableDriverBSONSizeCheck; - - // Set ssl up if it's defined - if(this.ssl) { - this.socketOptions.ssl = true; - // Set ssl validation - this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null; - // Set certificate to present - this.socketOptions.sslCert = this.sslCert; - // Set certificate to present - this.socketOptions.sslKey = this.sslKey; - // Password to unlock private key - this.socketOptions.sslPass = this.sslPass; - } - - // Set up logger if any set - this.logger = this.options.logger != null - && (typeof this.options.logger.debug == 'function') - && (typeof this.options.logger.error == 'function') - && (typeof this.options.logger.log == 'function') - ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}; - - // Just keeps list of events we allow - this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[]}; - // Internal state of server connection - this._serverState = 'disconnected'; - // Contains state information about server connection - this._state = {'runtimeStats': {'queryStats':new RunningStats()}}; - // Do we record server stats or not - this.recordQueryStats = false; - - // Allow setting the socketTimeoutMS on all connections - // to work around issues such as secondaries blocking due to compaction - utils.setSocketTimeoutProperty(this, this.socketOptions); -}; - -/** - * @ignore - */ -inherits(Server, Base); - -// -// Deprecated, USE ReadPreferences class -// -Server.READ_PRIMARY = ReadPreference.PRIMARY; -Server.READ_SECONDARY = ReadPreference.SECONDARY_PREFERRED; -Server.READ_SECONDARY_ONLY = ReadPreference.SECONDARY; - -/** - * Always ourselves - * @ignore - */ -Server.prototype.setReadPreference = function(readPreference) { - this._readPreference = readPreference; -} - -/** - * @ignore - */ -Server.prototype.isMongos = function() { - return this.isMasterDoc != null && this.isMasterDoc['msg'] == "isdbgrid" ? true : false; -} - -/** - * @ignore - */ -Server.prototype._isUsed = function() { - return this._used; -} - -/** - * @ignore - */ -Server.prototype.close = function(callback) { - // Set server status as disconnected - this._serverState = 'destroyed'; - // Remove all local listeners - this.removeAllListeners(); - - if(this.connectionPool != null) { - // Remove all the listeners on the pool so it does not fire messages all over the place - this.connectionPool.removeAllEventListeners(); - // Close the connection if it's open - this.connectionPool.stop(true); - } - - // Emit close event - if(this.db && !this.isSetMember()) { - var self = this; - processor(function() { - self._emitAcrossAllDbInstances(self, null, "close", null, null, true) - }) - - // Flush out any remaining call handlers - self._flushAllCallHandlers(utils.toError("Connection Closed By Application")); - } - - // Peform callback if present - if(typeof callback === 'function') callback(null); -}; - -Server.prototype.isDestroyed = function() { - return this._serverState == 'destroyed'; -} - -/** - * @ignore - */ -Server.prototype.isConnected = function() { - return this.connectionPool != null && this.connectionPool.isConnected(); -} - -/** - * @ignore - */ -Server.prototype.canWrite = Server.prototype.isConnected; -Server.prototype.canRead = Server.prototype.isConnected; - -Server.prototype.isAutoReconnect = function() { - if(this.isSetMember()) return false; - return this.options.auto_reconnect != null ? this.options.auto_reconnect : true; -} - -/** - * @ignore - */ -Server.prototype.allServerInstances = function() { - return [this]; -} - -/** - * @ignore - */ -Server.prototype.isSetMember = function() { - return this.replicasetInstance != null || this.mongosInstance != null; -} - -/** - * @ignore - */ -Server.prototype.setSocketOptions = function(options) { - var connections = this.allRawConnections(); - for(var i = 0; i < connections.length; i++) { - connections[i].setSocketOptions(options); - } -} - -/** - * Assigns a replica set to this `server`. - * - * @param {ReplSet} replset - * @ignore - */ -Server.prototype.assignReplicaSet = function (replset) { - this.replicasetInstance = replset; - this.inheritReplSetOptionsFrom(replset); - this.enableRecordQueryStats(replset.recordQueryStats); -} - -/** - * Takes needed options from `replset` and overwrites - * our own options. - * - * @param {ReplSet} replset - * @ignore - */ -Server.prototype.inheritReplSetOptionsFrom = function (replset) { - this.socketOptions = {}; - this.socketOptions.connectTimeoutMS = replset.options.socketOptions.connectTimeoutMS || 30000; - - if(replset.options.ssl) { - // Set ssl on - this.socketOptions.ssl = true; - // Set ssl validation - this.socketOptions.sslValidate = replset.options.sslValidate == null ? false : replset.options.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.socketOptions.sslCA = Array.isArray(replset.options.sslCA) ? replset.options.sslCA : null; - // Set certificate to present - this.socketOptions.sslCert = replset.options.sslCert; - // Set certificate to present - this.socketOptions.sslKey = replset.options.sslKey; - // Password to unlock private key - this.socketOptions.sslPass = replset.options.sslPass; - } - - // If a socket option object exists clone it - if(utils.isObject(replset.options.socketOptions)) { - var keys = Object.keys(replset.options.socketOptions); - for(var i = 0; i < keys.length; i++) - this.socketOptions[keys[i]] = replset.options.socketOptions[keys[i]]; - } -} - -/** - * Opens this server connection. - * - * @ignore - */ -Server.prototype.connect = function(dbInstance, options, callback) { - if('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - var self = this; - // Save the options - this.options = options; - - // Currently needed to work around problems with multiple connections in a pool with ssl - // TODO fix if possible - if(this.ssl == true) { - // Set up socket options for ssl - this.socketOptions.ssl = true; - // Set ssl validation - this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null; - // Set certificate to present - this.socketOptions.sslCert = this.sslCert; - // Set certificate to present - this.socketOptions.sslKey = this.sslKey; - // Password to unlock private key - this.socketOptions.sslPass = this.sslPass; - } - - // Let's connect - var server = this; - // Let's us override the main receiver of events - var eventReceiver = options.eventReceiver != null ? options.eventReceiver : this; - // Save reference to dbInstance - this.db = dbInstance; // `db` property matches ReplSet and Mongos - this.dbInstances = [dbInstance]; - - // Force connection pool if there is one - if(server.connectionPool) server.connectionPool.stop(); - // Set server state to connecting - this._serverState = 'connecting'; - - if(server.connectionPool != null) { - // Remove all the listeners on the pool so it does not fire messages all over the place - this.connectionPool.removeAllEventListeners(); - // Close the connection if it's open - this.connectionPool.stop(true); - } - - this.connectionPool = new ConnectionPool(this.host, this.port, this.poolSize, dbInstance.bson, this.socketOptions); - var connectionPool = this.connectionPool; - // If ssl is not enabled don't wait between the pool connections - if(this.ssl == null || !this.ssl) connectionPool._timeToWait = null; - // Set logger on pool - connectionPool.logger = this.logger; - connectionPool.bson = dbInstance.bson; - - // Set basic parameters passed in - var returnIsMasterResults = options.returnIsMasterResults == null ? false : options.returnIsMasterResults; - - // Create a default connect handler, overriden when using replicasets - var connectCallback = function(_server) { - return function(err, reply) { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - - // Assign the server - _server = _server != null ? _server : server; - - // If something close down the connection and removed the callback before - // proxy killed connection etc, ignore the erorr as close event was isssued - if(err != null && internalCallback == null) return; - // Internal callback - if(err != null) return internalCallback(err, null, _server); - if(reply == null || reply.documents == null) return internalCallback(utils.toError("server failed to respond", null, _server)); - _server.master = reply.documents[0].ismaster == 1 ? true : false; - _server.connectionPool.setMaxBsonSize(reply.documents[0].maxBsonObjectSize); - _server.connectionPool.setMaxMessageSizeBytes(reply.documents[0].maxMessageSizeBytes); - _server.connectionPool.setMaxWriteBatchSize(reply.documents[0].maxWriteBatchSize); - // Set server state to connEcted - _server._serverState = 'connected'; - // Set server as connected - _server.connected = true; - // Save document returned so we can query it - _server.isMasterDoc = reply.documents[0]; - - if(self.emitOpen) { - _server._emitAcrossAllDbInstances(_server, eventReceiver, "open", null, returnIsMasterResults ? reply : null, null); - self.emitOpen = false; - } else { - _server._emitAcrossAllDbInstances(_server, eventReceiver, "reconnect", null, returnIsMasterResults ? reply : null, null); - } - - // Set server capabilities - server.serverCapabilities = new ServerCapabilities(_server.isMasterDoc); - - // Set server capabilities on all the connections - var connections = connectionPool.getAllConnections(); - for(var i = 0; i < connections.length; i++) { - connections[i].serverCapabilities = server.serverCapabilities; - } - - // If we have it set to returnIsMasterResults - if(returnIsMasterResults) { - internalCallback(null, reply, _server); - } else { - internalCallback(null, dbInstance, _server); - } - } - }; - - // Let's us override the main connect callback - var connectHandler = options.connectHandler == null ? connectCallback(server) : options.connectHandler; - - // Set up on connect method - connectionPool.on("poolReady", function() { - // Create db command and Add the callback to the list of callbacks by the request id (mapping outgoing messages to correct callbacks) - var db_command = DbCommand.NcreateIsMasterCommand(dbInstance, dbInstance.databaseName); - // Check out a reader from the pool - var connection = connectionPool.checkoutConnection(); - // Register handler for messages - server._registerHandler(db_command, false, connection, connectHandler); - // Write the command out - connection.write(db_command); - }) - - // Set up item connection - connectionPool.on("message", function(message) { - // Attempt to parse the message - try { - // Create a new mongo reply - var mongoReply = new MongoReply() - // Parse the header - mongoReply.parseHeader(message, connectionPool.bson) - - // If message size is not the same as the buffer size - // something went terribly wrong somewhere - if(mongoReply.messageLength != message.length) { - // Emit the error - if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", new Error("bson length is different from message length"), server); - // Remove all listeners - server.removeAllListeners(); - } else { - var startDate = new Date().getTime(); - - // Callback instance - var callbackInfo = server._findHandler(mongoReply.responseTo.toString()); - // Abort if not a valid callbackInfo, don't try to call it - if(callbackInfo == null || callbackInfo.info == null) return; - - // The command executed another request, log the handler again under that request id - if(mongoReply.requestId > 0 && mongoReply.cursorId.toString() != "0" - && callbackInfo && callbackInfo.info && callbackInfo.info.exhaust) { - server._reRegisterHandler(mongoReply.requestId, callbackInfo); - } - - // Parse the body - mongoReply.parseBody(message, connectionPool.bson, callbackInfo.info.raw, function(err) { - if(err != null) { - // If pool connection is already closed - if(server._serverState === 'disconnected') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // Remove all listeners and close the connection pool - server.removeAllListeners(); - connectionPool.stop(true); - - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(err, null, server); - } else if(server.isSetMember()) { - if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", utils.toError(err), server); - } else { - if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", utils.toError(err), server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(err); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true); - } - // Short cut - return; - } - - // Let's record the stats info if it's enabled - if(server.recordQueryStats == true && server._state['runtimeStats'] != null - && server._state.runtimeStats['queryStats'] instanceof RunningStats) { - // Add data point to the running statistics object - server._state.runtimeStats.queryStats.push(new Date().getTime() - callbackInfo.info.start); - } - - // Dispatch the call - server._callHandler(mongoReply.responseTo, mongoReply, null); - - // If we have an error about the server not being master or primary - if((mongoReply.responseFlag & (1 << 1)) != 0 - && mongoReply.documents[0].code - && mongoReply.documents[0].code == 13436) { - server.close(); - } - }); - } - } catch (err) { - // Throw error in next tick - processor(function() { - throw err; - }) - } - }); - - // Handle timeout - connectionPool.on("timeout", function(err) { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(err, null, server); - } else if(server.isSetMember()) { - if(server.listeners("timeout") && server.listeners("timeout").length > 0) server.emit("timeout", err, server); - } else { - if(eventReceiver.listeners("timeout") && eventReceiver.listeners("timeout").length > 0) eventReceiver.emit("timeout", err, server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(err); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "timeout", err, server, true); - } - - // If we have autoConnect enabled let's fire up an attempt to reconnect - if(server.isAutoReconnect() - && !server.isSetMember() - && (server._serverState != 'destroyed') - && !server._reconnectInProgreess) { - // Set the number of retries - server._reconnect_retries = server.db.numberOfRetries; - // Attempt reconnect - server._reconnectInProgreess = true; - setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - }); - - // Handle errors - connectionPool.on("error", function(message, connection, error_options) { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - - // Set server state to disconnected - server._serverState = 'disconnected'; - // Error message - var error_message = new Error(message && message.err ? message.err : message); - // Error message coming from ssl - if(error_options && error_options.ssl) error_message.ssl = true; - - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(error_message, null, server); - } else if(server.isSetMember()) { - if(server.listeners("error") && server.listeners("error").length > 0) server.emit("error", error_message, server); - } else { - if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", error_message, server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(error_message); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "error", error_message, server, true); - } - - // If we have autoConnect enabled let's fire up an attempt to reconnect - if(server.isAutoReconnect() - && !server.isSetMember() - && (server._serverState != 'destroyed') - && !server._reconnectInProgreess) { - - // Set the number of retries - server._reconnect_retries = server.db.numberOfRetries; - // Attempt reconnect - server._reconnectInProgreess = true; - setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - }); - - // Handle close events - connectionPool.on("close", function() { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // If we have a callback return the error - if(typeof callback == 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(new Error("connection closed"), null, server); - } else if(server.isSetMember()) { - if(server.listeners("close") && server.listeners("close").length > 0) server.emit("close", new Error("connection closed"), server); - } else { - if(eventReceiver.listeners("close") && eventReceiver.listeners("close").length > 0) eventReceiver.emit("close", new Error("connection closed"), server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(new Error("connection closed")); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "close", server, null, true); - } - - // If we have autoConnect enabled let's fire up an attempt to reconnect - if(server.isAutoReconnect() - && !server.isSetMember() - && (server._serverState != 'destroyed') - && !server._reconnectInProgreess) { - - // Set the number of retries - server._reconnect_retries = server.db.numberOfRetries; - // Attempt reconnect - server._reconnectInProgreess = true; - setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - }); - - /** - * @ignore - */ - var __attemptReconnect = function(server) { - return function() { - // Attempt reconnect - server.connect(server.db, server.options, function(err, result) { - server._reconnect_retries = server._reconnect_retries - 1; - - if(err) { - // Retry - if(server._reconnect_retries == 0 || server._serverState == 'destroyed') { - server._serverState = 'connected'; - server._reconnectInProgreess = false - // Fire all callback errors - return server.__executeAllCallbacksWithError(new Error("failed to reconnect to server")); - } else { - return setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - } else { - // Set as authenticating (isConnected will be false) - server._serverState = 'authenticating'; - // Apply any auths, we don't try to catch any errors here - // as there are nowhere to simply propagate them to - self._apply_auths(server.db, function(err, result) { - server._serverState = 'connected'; - server._reconnectInProgreess = false; - - // Execute any buffered reads and writes - server._commandsStore.execute_queries(); - server._commandsStore.execute_writes(); - // Emit reconnect event - server.emit('reconnect'); - }); - } - }); - } - } - - // If we have a parser error we are in an unknown state, close everything and emit - // error - connectionPool.on("parseError", function(err) { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(utils.toError(err), null, server); - } else if(server.isSetMember()) { - if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", utils.toError(err), server); - } else { - if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", utils.toError(err), server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(utils.toError(err)); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true); - // Emit close event - server._emitAcrossAllDbInstances(server, eventReceiver, "close", new Error("connection closed"), null, true); - } - }); - - // Boot up connection poole, pass in a locator of callbacks - connectionPool.start(); -} - -/** - * @ignore - */ -Server.prototype.allRawConnections = function() { - return this.connectionPool != null ? this.connectionPool.getAllConnections() : []; -} - -/** - * Check if a writer can be provided - * @ignore - */ -var canCheckoutWriter = function(self, read) { - var error = null; - // We cannot write to an arbiter or secondary server - if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true) { - error = new Error("Cannot write to an arbiter"); - error.code = -5000; - } if(self.isMasterDoc && self.isMasterDoc['secondary'] == true) { - error = new Error("Cannot write to a secondary"); - error.code = -5000; - } else if(read == true && self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc && self.isMasterDoc['ismaster'] == true) { - error = new Error("Cannot read from primary when secondary only specified"); - error.code = -5000; - } else if(!self.isMasterDoc) { - error = new Error("Cannot determine state of server"); - error.code = -5000; - } - - // Return no error - return error; -} - -/** - * @ignore - */ -Server.prototype.checkoutWriter = function(read) { - if(this._serverState == 'disconnected' || this._serverState == 'destroyed') - return null; - if(read == true) return this.connectionPool.checkoutConnection(); - // Check if are allowed to do a checkout (if we try to use an arbiter f.ex) - var result = canCheckoutWriter(this, read); - // If the result is null check out a writer - if(result == null && this.connectionPool != null) { - return this.connectionPool.checkoutConnection(); - } else if(result == null) { - return null; - } else { - return result; - } -} - -/** - * Check if a reader can be provided - * @ignore - */ -var canCheckoutReader = function(self) { - // We cannot write to an arbiter or secondary server - if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true && self.isSetMember()) { - return new Error("Cannot write to an arbiter"); - } else if(self._readPreference != null) { - // If the read preference is Primary and the instance is not a master return an error - if((self._readPreference == ReadPreference.PRIMARY) && self.isMasterDoc && self.isMasterDoc['ismaster'] != true) { - return new Error("Read preference is Server.PRIMARY and server is not master"); - } else if(self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc && self.isMasterDoc['ismaster'] == true) { - return new Error("Cannot read from primary when secondary only specified"); - } - } else if(!self.isMasterDoc) { - return new Error("Cannot determine state of server"); - } - - // Return no error - return null; -} - -/** - * @ignore - */ -Server.prototype.checkoutReader = function(read) { - if(this._serverState == 'disconnected' || this._serverState == 'destroyed') - return null; - // Check if are allowed to do a checkout (if we try to use an arbiter f.ex) - var result = canCheckoutReader(this); - // If the result is null check out a writer - if(result == null && this.connectionPool != null) { - return this.connectionPool.checkoutConnection(); - } else if(result == null) { - return null; - } else { - return result; - } -} - -/** - * @ignore - */ -Server.prototype.enableRecordQueryStats = function(enable) { - this.recordQueryStats = enable; -} - -/** - * Internal statistics object used for calculating average and standard devitation on - * running queries - * @ignore - */ -var RunningStats = function() { - var self = this; - this.m_n = 0; - this.m_oldM = 0.0; - this.m_oldS = 0.0; - this.m_newM = 0.0; - this.m_newS = 0.0; - - // Define getters - Object.defineProperty(this, "numDataValues", { enumerable: true - , get: function () { return this.m_n; } - }); - - Object.defineProperty(this, "mean", { enumerable: true - , get: function () { return (this.m_n > 0) ? this.m_newM : 0.0; } - }); - - Object.defineProperty(this, "variance", { enumerable: true - , get: function () { return ((this.m_n > 1) ? this.m_newS/(this.m_n - 1) : 0.0); } - }); - - Object.defineProperty(this, "standardDeviation", { enumerable: true - , get: function () { return Math.sqrt(this.variance); } - }); - - Object.defineProperty(this, "sScore", { enumerable: true - , get: function () { - var bottom = this.mean + this.standardDeviation; - if(bottom == 0) return 0; - return ((2 * this.mean * this.standardDeviation)/(bottom)); - } - }); -} - -/** - * @ignore - */ -RunningStats.prototype.push = function(x) { - // Update the number of samples - this.m_n = this.m_n + 1; - - // See Knuth TAOCP vol 2, 3rd edition, page 232 - if(this.m_n == 1) { - this.m_oldM = this.m_newM = x; - this.m_oldS = 0.0; - } else { - this.m_newM = this.m_oldM + (x - this.m_oldM) / this.m_n; - this.m_newS = this.m_oldS + (x - this.m_oldM) * (x - this.m_newM); - // set up for next iteration - this.m_oldM = this.m_newM; - this.m_oldS = this.m_newS; - } -} - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "autoReconnect", { enumerable: true - , get: function () { - return this.options['auto_reconnect'] == null ? false : this.options['auto_reconnect']; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "connection", { enumerable: true - , get: function () { - return this.internalConnection; - } - , set: function(connection) { - this.internalConnection = connection; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "master", { enumerable: true - , get: function () { - return this.internalMaster; - } - , set: function(value) { - this.internalMaster = value; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "primary", { enumerable: true - , get: function () { - return this; - } -}); - -/** - * Getter for query Stats - * @ignore - */ -Object.defineProperty(Server.prototype, "queryStats", { enumerable: true - , get: function () { - return this._state.runtimeStats.queryStats; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "runtimeStats", { enumerable: true - , get: function () { - return this._state.runtimeStats; - } -}); - -/** - * Get Read Preference method - * @ignore - */ -Object.defineProperty(Server.prototype, "readPreference", { enumerable: true - , get: function () { - if(this._readPreference == null && this.readSecondary) { - return Server.READ_SECONDARY; - } else if(this._readPreference == null && !this.readSecondary) { - return Server.READ_PRIMARY; - } else { - return this._readPreference; - } - } -}); - -/** - * @ignore - */ -exports.Server = Server; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js deleted file mode 100755 index 34df6b1f..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js +++ /dev/null @@ -1,57 +0,0 @@ -var ServerCapabilities = function(isMasterResult) { - // Capabilities - var aggregationCursor = false; - var writeCommands = false; - var textSearch = false; - var authCommands = false; - var listCollections = false; - var listIndexes = false; - var maxNumberOfDocsInBatch = isMasterResult.maxWriteBatchSize || 1000; - - if(isMasterResult.minWireVersion >= 0) { - textSearch = true; - } - - if(isMasterResult.maxWireVersion >= 1) { - aggregationCursor = true; - authCommands = true; - } - - if(isMasterResult.maxWireVersion >= 2) { - writeCommands = true; - } - - if(isMasterResult.maxWireVersion >= 3) { - listCollections = true; - listIndexes = true; - } - - // If no min or max wire version set to 0 - if(isMasterResult.minWireVersion == null) { - isMasterResult.minWireVersion = 0; - } - - if(isMasterResult.maxWireVersion == null) { - isMasterResult.maxWireVersion = 0; - } - - // Map up read only parameters - setup_get_property(this, "hasAggregationCursor", aggregationCursor); - setup_get_property(this, "hasWriteCommands", writeCommands); - setup_get_property(this, "hasTextSearch", textSearch); - setup_get_property(this, "hasAuthCommands", authCommands); - setup_get_property(this, "hasListCollectionsCommand", listCollections); - setup_get_property(this, "hasListIndexesCommand", listIndexes); - setup_get_property(this, "minWireVersion", isMasterResult.minWireVersion); - setup_get_property(this, "maxWireVersion", isMasterResult.maxWireVersion); - setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch); -} - -var setup_get_property = function(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true - , get: function () { return value; } - }); -} - -exports.ServerCapabilities = ServerCapabilities; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/url_parser.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/url_parser.js deleted file mode 100755 index 4db9579d..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/connection/url_parser.js +++ /dev/null @@ -1,265 +0,0 @@ -var fs = require('fs'), - ReadPreference = require('./read_preference').ReadPreference; - -exports.parse = function(url, options) { - // Ensure we have a default options object if none set - options = options || {}; - // Variables - var connection_part = ''; - var auth_part = ''; - var query_string_part = ''; - var dbName = 'admin'; - - // Must start with mongodb - if(url.indexOf("mongodb://") != 0) - throw Error("URL must be in the format mongodb://user:pass@host:port/dbname"); - // If we have a ? mark cut the query elements off - if(url.indexOf("?") != -1) { - query_string_part = url.substr(url.indexOf("?") + 1); - connection_part = url.substring("mongodb://".length, url.indexOf("?")) - } else { - connection_part = url.substring("mongodb://".length); - } - - // Check if we have auth params - if(connection_part.indexOf("@") != -1) { - auth_part = connection_part.split("@")[0]; - connection_part = connection_part.split("@")[1]; - } - - // Check if the connection string has a db - if(connection_part.indexOf(".sock") != -1) { - if(connection_part.indexOf(".sock/") != -1) { - dbName = connection_part.split(".sock/")[1]; - connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); - } - } else if(connection_part.indexOf("/") != -1) { - dbName = connection_part.split("/")[1]; - connection_part = connection_part.split("/")[0]; - } - - // Result object - var object = {}; - - // Pick apart the authentication part of the string - var authPart = auth_part || ''; - var auth = authPart.split(':', 2); - if(options['uri_decode_auth']){ - auth[0] = decodeURIComponent(auth[0]); - if(auth[1]){ - auth[1] = decodeURIComponent(auth[1]); - } - } - - // Add auth to final object if we have 2 elements - if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]}; - - // Variables used for temporary storage - var hostPart; - var urlOptions; - var servers; - var serverOptions = {socketOptions: {}}; - var dbOptions = {read_preference_tags: []}; - var replSetServersOptions = {socketOptions: {}}; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = {}; - - // Let's check if we are using a domain socket - if(url.match(/\.sock/)) { - // Split out the socket part - var domainSocket = url.substring( - url.indexOf("mongodb://") + "mongodb://".length - , url.lastIndexOf(".sock") + ".sock".length); - // Clean out any auth stuff if any - if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1]; - servers = [{domain_socket: domainSocket}]; - } else { - // Split up the db - hostPart = connection_part; - // Parse all server results - servers = hostPart.split(',').map(function(h) { - var _host, _port, ipv6match; - //check if it matches [IPv6]:port, where the port number is optional - if ((ipv6match = /\[([^\]]+)\](?:\:(.+))?/.exec(h))) { - _host = ipv6match[1]; - _port = parseInt(ipv6match[2], 10) || 27017; - } else { - //otherwise assume it's IPv4, or plain hostname - var hostPort = h.split(':', 2); - _host = hostPort[0] || 'localhost'; - _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; - // Check for localhost?safe=true style case - if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0]; - } - // Return the mapped object - return {host: _host, port: _port}; - }); - } - - // Get the db name - object.dbName = dbName || 'admin'; - // Split up all the options - urlOptions = (query_string_part || '').split(/[&;]/); - // Ugh, we have to figure out which options go to which constructor manually. - urlOptions.forEach(function(opt) { - if(!opt) return; - var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1]; - // Options implementations - switch(name) { - case 'slaveOk': - case 'slave_ok': - serverOptions.slave_ok = (value == 'true'); - dbOptions.slaveOk = (value == 'true'); - break; - case 'maxPoolSize': - case 'poolSize': - serverOptions.poolSize = parseInt(value, 10); - replSetServersOptions.poolSize = parseInt(value, 10); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = (value == 'true'); - break; - case 'minPoolSize': - throw new Error("minPoolSize not supported"); - case 'maxIdleTimeMS': - throw new Error("maxIdleTimeMS not supported"); - case 'waitQueueMultiple': - throw new Error("waitQueueMultiple not supported"); - case 'waitQueueTimeoutMS': - throw new Error("waitQueueTimeoutMS not supported"); - case 'uuidRepresentation': - throw new Error("uuidRepresentation not supported"); - case 'ssl': - if(value == 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - break; - } - serverOptions.ssl = (value == 'true'); - replSetServersOptions.ssl = (value == 'true'); - break; - case 'replicaSet': - case 'rs_name': - replSetServersOptions.rs_name = value; - break; - case 'reconnectWait': - replSetServersOptions.reconnectWait = parseInt(value, 10); - break; - case 'retries': - replSetServersOptions.retries = parseInt(value, 10); - break; - case 'readSecondary': - case 'read_secondary': - replSetServersOptions.read_secondary = (value == 'true'); - break; - case 'fsync': - dbOptions.fsync = (value == 'true'); - break; - case 'journal': - dbOptions.journal = (value == 'true'); - break; - case 'safe': - dbOptions.safe = (value == 'true'); - break; - case 'nativeParser': - case 'native_parser': - dbOptions.native_parser = (value == 'true'); - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - break; - case 'w': - dbOptions.w = parseInt(value, 10); - if(isNaN(dbOptions.w)) dbOptions.w = value; - break; - case 'authSource': - dbOptions.authSource = value; - break; - case 'gssapiServiceName': - dbOptions.gssapiServiceName = value; - break; - case 'authMechanism': - if(value == 'GSSAPI') { - // If no password provided decode only the principal - if(object.auth == null) { - var urlDecodeAuthPart = decodeURIComponent(authPart); - if(urlDecodeAuthPart.indexOf("@") == -1) throw new Error("GSSAPI requires a provided principal"); - object.auth = {user: urlDecodeAuthPart, password: null}; - } else { - object.auth.user = decodeURIComponent(object.auth.user); - } - } else if(value == 'MONGODB-X509') { - object.auth = {user: decodeURIComponent(authPart)}; - } - - // Only support GSSAPI or MONGODB-CR for now - if(value != 'GSSAPI' - && value != 'MONGODB-X509' - && value != 'SCRAM-SHA-1' - && value != 'MONGODB-CR' - && value != 'PLAIN') - throw new Error("only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism"); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'wtimeoutMS': - dbOptions.wtimeout = parseInt(value, 10); - break; - case 'readPreference': - if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest"); - dbOptions.read_preference = value; - break; - case 'readPreferenceTags': - // Decode the value - value = decodeURIComponent(value); - // Contains the tag object - var tagObject = {}; - if(value == null || value == '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - var tags = value.split(/\,/); - for(var i = 0; i < tags.length; i++) { - var parts = tags[i].trim().split(/\:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - break; - default: - break; - } - }); - - // No tags: should be null (not []) - if(dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } - - // Validate if there are an invalid write concern combinations - if((dbOptions.w == -1 || dbOptions.w == 0) && ( - dbOptions.journal == true - || dbOptions.fsync == true - || dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync") - - // If no read preference set it to primary - if(!dbOptions.read_preference) dbOptions.read_preference = 'primary'; - - // Add servers to result - object.servers = servers; - // Returned parsed object - return object; -} diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/cursor.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/cursor.js deleted file mode 100755 index 102d0b21..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/cursor.js +++ /dev/null @@ -1,1058 +0,0 @@ -var QueryCommand = require('./commands/query_command').QueryCommand, - GetMoreCommand = require('./commands/get_more_command').GetMoreCommand, - KillCursorCommand = require('./commands/kill_cursor_command').KillCursorCommand, - Long = require('bson').Long, - ReadPreference = require('./connection/read_preference').ReadPreference, - CursorStream = require('./cursorstream'), - timers = require('timers'), - utils = require('./utils'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('./utils').processor(); - -/** - * Constructor for a cursor object that handles all the operations on query result - * using find. This cursor object is unidirectional and cannot traverse backwards. Clients should not be creating a cursor directly, - * but use find to acquire a cursor. (INTERNAL TYPE) - * - * Options - * - **skip** {Number} skip number of documents to skip. - * - **limit** {Number}, limit the number of results to return. -1 has a special meaning and is used by Db.eval. A value of 1 will also be treated as if it were -1. - * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * - **hint** {Object}, hint force the query to use a specific index. - * - **explain** {Boolean}, explain return the explaination of the query. - * - **snapshot** {Boolean}, snapshot Snapshot mode assures no duplicates are returned. - * - **timeout** {Boolean}, timeout allow the query to timeout. - * - **tailable** {Boolean}, tailable allow the cursor to be tailable. - * - **awaitdata** {Boolean}, awaitdata allow the cursor to wait for data, only applicable for tailable cursor. - * - **oplogReplay** {Boolean}, sets an internal flag, only applicable for tailable cursor. - * - **batchSize** {Number}, batchSize the number of the subset of results to request the database to return for every request. This should initially be greater than 1 otherwise the database will automatically close the cursor. The batch size can be set to 1 with cursorInstance.batchSize after performing the initial query to the database. - * - **raw** {Boolean}, raw return all query documents as raw buffers (default false). - * - **read** {Boolean}, read specify override of read from source (primary/secondary). - * - **returnKey** {Boolean}, returnKey only return the index key. - * - **maxScan** {Number}, maxScan limit the number of items to scan. - * - **min** {Number}, min set index bounds. - * - **max** {Number}, max set index bounds. - * - **maxTimeMS** {Number}, number of miliseconds to wait before aborting the query. - * - **showDiskLoc** {Boolean}, showDiskLoc show disk location of results. - * - **comment** {String}, comment you can put a $comment field on a query to make looking in the profiler logs simpler. - * - **numberOfRetries** {Number}, numberOfRetries if using awaidata specifies the number of times to retry on timeout. - * - **dbName** {String}, dbName override the default dbName. - * - **tailableRetryInterval** {Number}, tailableRetryInterval specify the miliseconds between getMores on tailable cursor. - * - **exhaust** {Boolean}, exhaust have the server send all the documents at once as getMore packets. - * - **partial** {Boolean}, partial have the sharded system return a partial result from mongos. - * - * @class Represents a Cursor. - * @param {Db} db the database object to work with. - * @param {Collection} collection the collection to query. - * @param {Object} selector the query selector. - * @param {Object} fields an object containing what fields to include or exclude from objects returned. - * @param {Object} [options] additional options for the collection. -*/ -function Cursor(db, collection, selector, fields, options) { - this.db = db; - this.collection = collection; - this.selector = selector; - this.fields = fields; - options = !options ? {} : options; - - this.skipValue = options.skip == null ? 0 : options.skip; - this.limitValue = options.limit == null ? 0 : options.limit; - this.sortValue = options.sort; - this.hint = options.hint; - this.explainValue = options.explain; - this.snapshot = options.snapshot; - this.timeout = options.timeout == null ? true : options.timeout; - this.tailable = options.tailable; - this.awaitdata = options.awaitdata; - this.oplogReplay = options.oplogReplay; - this.numberOfRetries = options.numberOfRetries == null ? 5 : options.numberOfRetries; - this.currentNumberOfRetries = this.numberOfRetries; - this.batchSizeValue = options.batchSize == null ? 0 : options.batchSize; - this.raw = options.raw == null ? false : options.raw; - this.readPreference = options.readPreference == null ? ReadPreference.PRIMARY : options.readPreference; - this.returnKey = options.returnKey; - this.maxScan = options.maxScan; - this.min = options.min; - this.max = options.max; - this.showDiskLoc = options.showDiskLoc; - this.comment = options.comment; - this.tailableRetryInterval = options.tailableRetryInterval || 100; - this.exhaust = options.exhaust || false; - this.partial = options.partial || false; - this.slaveOk = options.slaveOk || false; - this.maxTimeMSValue = options.maxTimeMS; - this.connection = options.connection; - this.transforms = options.transforms; - - this.totalNumberOfRecords = 0; - this.items = []; - this.cursorId = Long.fromInt(0); - - // This name - this.dbName = options.dbName; - - // State variables for the cursor - this.state = Cursor.INIT; - // Keep track of the current query run - this.queryRun = false; - this.getMoreTimer = false; - - // If we are using a specific db execute against it - if(this.dbName != null) { - this.collectionName = this.dbName + "." + this.collection.collectionName; - } else { - this.collectionName = (this.db.databaseName ? this.db.databaseName + "." : '') + this.collection.collectionName; - } -} - -/** - * Clones a given cursor but uses new options - * @param {Cursor} cursor the cursor to clone. - * @return {Object} [options] additional options for the collection when cloning. - */ -Cursor.cloneWithOptions = function(cursor, options) { - return new Cursor(cursor.db, cursor.collection, cursor.selector, cursor.fields, options); -} - -/** - * Resets this cursor to its initial state. All settings like the query string, - * tailable, batchSizeValue, skipValue and limits are preserved. - * - * @return {Cursor} returns itself with rewind applied. - * @api public - */ -Cursor.prototype.rewind = function() { - var self = this; - - if (self.state != Cursor.INIT) { - if (self.state != Cursor.CLOSED) { - self.close(function() {}); - } - - self.numberOfReturned = 0; - self.totalNumberOfRecords = 0; - self.items = []; - self.cursorId = Long.fromInt(0); - self.state = Cursor.INIT; - self.queryRun = false; - } - - return self; -} - - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previouly accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * - * @param {Function} callback This will be called after executing this method successfully. The first parameter will contain the Error object if an error occured, or null otherwise. The second parameter will contain an array of BSON deserialized objects as a result of the query. - * @return {null} - * @api public - */ -Cursor.prototype.toArray = function(callback) { - var self = this; - - if(!callback) { - throw new Error('callback is mandatory'); - } - - if(this.tailable) { - callback(new Error("Tailable cursor cannot be converted to array"), null); - } else if(this.state != Cursor.CLOSED) { - // return toArrayExhaust(self, callback); - // If we are using exhaust we can't use the quick fire method - if(self.exhaust) return toArrayExhaust(self, callback); - // Quick fire using trampoline to avoid nextTick - self.nextObject({noReturn: true}, function(err, result) { - if(err) return callback(utils.toError(err), null); - if(self.cursorId.toString() == "0") { - self.state = Cursor.CLOSED; - - // If we have a transform - if(typeof self.transforms == 'function') { - self.items = self.transforms(self.items); - } - - // Return the documents - return callback(null, self.items); - } - - // Let's issue getMores until we have no more records waiting - getAllByGetMore(self, function(err, done) { - self.state = Cursor.CLOSED; - if(err) return callback(utils.toError(err), null); - // Let's release the internal list - var items = self.items; - self.items = null; - - // If we have a transform - if(typeof self.transforms == 'function') { - items = self.transforms(items); - } - - // Return all the items - callback(null, items); - }); - }) - - } else { - callback(new Error("Cursor is closed"), null); - } -} - -var toArrayExhaust = function(self, callback) { - var items = []; - - self.each(function(err, item) { - if(err != null) { - return callback(utils.toError(err), null); - } - - if(item != null && Array.isArray(items)) { - items.push(item); - } else { - var resultItems = items; - items = null; - self.items = []; - callback(null, resultItems); - } - }); -} - -var getAllByGetMore = function(self, callback) { - getMore(self, {noReturn: true}, function(err, result) { - if(err) return callback(utils.toError(err)); - if(result == null) return callback(null, null); - if(self.cursorId.toString() == "0") return callback(null, null); - getAllByGetMore(self, callback); - }) -}; - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previouly accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * - * @param {Function} callback this will be called for while iterating every document of the query result. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the document. - * @return {null} - * @api public - */ -Cursor.prototype.each = function(callback) { - var self = this; - var fn; - - if (!callback) { - throw new Error('callback is mandatory'); - } - - if(this.state != Cursor.CLOSED) { - // If we are using exhaust we can't use the quick fire method - if(self.exhaust) return eachExhaust(self, callback); - // Quick fire using trampoline to avoid nextTick - if(this.items.length > 0) { - // Trampoline all the entries - while(fn = loop(self, callback)) fn(self, callback); - // Call each again - self.each(callback); - } else { - self.nextObject(function(err, item) { - - if(err) { - self.state = Cursor.CLOSED; - return callback(utils.toError(err), item); - } - - if(item == null) return callback(null, null); - callback(null, item); - self.each(callback); - }) - } - } else { - callback(new Error("Cursor is closed"), null); - } -}; - -// Special for exhaust command as we don't initiate the actual result sets -// the server just sends them as they arrive meaning we need to get the IO event -// loop happen so we can receive more data from the socket or we return to early -// after the first fetch and loose all the incoming getMore's automatically issued -// from the server. -var eachExhaust = function(self, callback) { - //FIX: stack overflow (on deep callback) (cred: https://github.com/limp/node-mongodb-native/commit/27da7e4b2af02035847f262b29837a94bbbf6ce2) - processor(function(){ - // Fetch the next object until there is no more objects - self.nextObject(function(err, item) { - if(err != null) return callback(err, null); - if(item != null) { - callback(null, item); - eachExhaust(self, callback); - } else { - // Close the cursor if done - self.state = Cursor.CLOSED; - callback(err, null); - } - }); - }); -} - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -var loop = function(self, callback) { - // No more items we are done - if(self.items.length == 0) return; - // Get the next document - var doc = self.items.shift(); - // Callback - callback(null, doc); - // Loop - return loop; -} - -/** - * Determines how many result the query for this cursor will return - * - * @param {Boolean} applySkipLimit if set to true will apply the skip and limits set on the cursor. Defaults to false. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the number of results or null if an error occured. - * @return {null} - * @api public - */ -Cursor.prototype.count = function(applySkipLimit, callback) { - if(typeof applySkipLimit == 'function') { - callback = applySkipLimit; - applySkipLimit = false; - } - - var options = {}; - if(applySkipLimit) { - if(typeof this.skipValue == 'number') options.skip = this.skipValue; - if(typeof this.limitValue == 'number') options.limit = this.limitValue; - } - - // If maxTimeMS set - if(typeof this.maxTimeMSValue == 'number') options.maxTimeMS = this.maxTimeMSValue; - // Do we have a hint add it to the options - if(this.hint) options.hint = this.hint; - - // Call count command - this.collection.count(this.selector, options, callback); -}; - -/** - * Sets the sort parameter of this cursor to the given value. - * - * This method has the following method signatures: - * (keyOrList, callback) - * (keyOrList, direction, callback) - * - * @param {String|Array|Object} keyOrList This can be a string or an array. If passed as a string, the string will be the field to sort. If passed an array, each element will represent a field to be sorted and should be an array that contains the format [string, direction]. - * @param {String|Number} direction this determines how the results are sorted. "asc", "ascending" or 1 for asceding order while "desc", "desceding or -1 for descending order. Note that the strings are case insensitive. - * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.sort = function(keyOrList, direction, callback) { - callback = callback || function(){}; - if(typeof direction === "function") { callback = direction; direction = null; } - - if(this.tailable) { - callback(new Error("Tailable cursor doesn't support sorting"), null); - } else if(this.queryRun == true || this.state == Cursor.CLOSED) { - callback(new Error("Cursor is closed"), null); - } else { - var order = keyOrList; - - if(direction != null) { - order = [[keyOrList, direction]]; - } - - this.sortValue = order; - callback(null, this); - } - return this; -}; - -/** - * Sets the limit parameter of this cursor to the given value. - * - * @param {Number} limit the new limit. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the limit given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.limit = function(limit, callback) { - if(this.tailable) { - if(callback) { - callback(new Error("Tailable cursor doesn't support limit"), null); - } else { - throw new Error("Tailable cursor doesn't support limit"); - } - } else if(this.queryRun == true || this.state == Cursor.CLOSED) { - if(callback) { - callback(new Error("Cursor is closed"), null); - } else { - throw new Error("Cursor is closed"); - } - } else { - if(limit != null && limit.constructor != Number) { - if(callback) { - callback(new Error("limit requires an integer"), null); - } else { - throw new Error("limit requires an integer"); - } - } else { - this.limitValue = limit; - if(callback) return callback(null, this); - } - } - - return this; -}; - -/** - * Specifies a time limit for a query operation. After the specified - * time is exceeded, the operation will be aborted and an error will be - * returned to the client. If maxTimeMS is null, no limit is applied. - * - * @param {Number} maxTimeMS the maxTimeMS for the query. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the limit given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.maxTimeMS = function(maxTimeMS, callback) { - if(typeof maxTimeMS != 'number') { - throw new Error("maxTimeMS must be a number"); - } - - // Save the maxTimeMS option - this.maxTimeMSValue = maxTimeMS; - // Return the cursor for chaining - return this; -}; - -/** - * Sets the read preference for the cursor - * - * @param {String} the read preference for the cursor, one of Server.READ_PRIMARY, Server.READ_SECONDARY, Server.READ_SECONDARY_ONLY - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the read preference given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.setReadPreference = function(readPreference, tags, callback) { - if(typeof tags == 'function') callback = tags; - - var _mode = readPreference != null && typeof readPreference == 'object' ? readPreference.mode : readPreference; - - if(this.queryRun == true || this.state == Cursor.CLOSED) { - if(callback == null) throw new Error("Cannot change read preference on executed query or closed cursor"); - callback(new Error("Cannot change read preference on executed query or closed cursor")); - } else if(_mode != null && _mode != 'primary' - && _mode != 'secondaryOnly' && _mode != 'secondary' - && _mode != 'nearest' && _mode != 'primaryPreferred' && _mode != 'secondaryPreferred') { - if(callback == null) throw new Error("only readPreference of primary, secondary, secondaryPreferred, primaryPreferred or nearest supported"); - callback(new Error("only readPreference of primary, secondary, secondaryPreferred, primaryPreferred or nearest supported")); - } else { - this.readPreference = readPreference; - if(callback != null) callback(null, this); - } - - return this; -} - -/** - * Sets the skip parameter of this cursor to the given value. - * - * @param {Number} skip the new skip value. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the skip value given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.skip = function(skip, callback) { - callback = callback || function(){}; - - if(this.tailable) { - callback(new Error("Tailable cursor doesn't support skip"), null); - } else if(this.queryRun == true || this.state == Cursor.CLOSED) { - callback(new Error("Cursor is closed"), null); - } else { - if(skip != null && skip.constructor != Number) { - callback(new Error("skip requires an integer"), null); - } else { - this.skipValue = skip; - callback(null, this); - } - } - - return this; -}; - -/** - * Sets the batch size parameter of this cursor to the given value. - * - * @param {Number} batchSize the new batch size. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the batchSize given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.batchSize = function(batchSize, callback) { - if(this.state == Cursor.CLOSED) { - if(callback != null) { - return callback(new Error("Cursor is closed"), null); - } else { - throw new Error("Cursor is closed"); - } - } else if(batchSize != null && batchSize.constructor != Number) { - if(callback != null) { - return callback(new Error("batchSize requires an integer"), null); - } else { - throw new Error("batchSize requires an integer"); - } - } else { - this.batchSizeValue = batchSize; - if(callback != null) return callback(null, this); - } - - return this; -}; - -/** - * The limit used for the getMore command - * - * @return {Number} The number of records to request per batch. - * @ignore - * @api private - */ -var limitRequest = function(self) { - var requestedLimit = self.limitValue; - var absLimitValue = Math.abs(self.limitValue); - var absBatchValue = Math.abs(self.batchSizeValue); - - if(absLimitValue > 0) { - if (absBatchValue > 0) { - requestedLimit = Math.min(absLimitValue, absBatchValue); - } - } else { - requestedLimit = self.batchSizeValue; - } - - return requestedLimit; -}; - - -/** - * Generates a QueryCommand object using the parameters of this cursor. - * - * @return {QueryCommand} The command object - * @ignore - * @api private - */ -var generateQueryCommand = function(self) { - // Unpack the options - var queryOptions = QueryCommand.OPTS_NONE; - if(!self.timeout) { - queryOptions |= QueryCommand.OPTS_NO_CURSOR_TIMEOUT; - } - - if(self.tailable) { - queryOptions |= QueryCommand.OPTS_TAILABLE_CURSOR; - self.skipValue = self.limitValue = 0; - - // if awaitdata is set - if(self.awaitdata) { - queryOptions |= QueryCommand.OPTS_AWAIT_DATA; - } - - // This sets an internal undocumented flag. Clients should not depend on its - // behavior! - if(self.oplogReplay) { - queryOptions |= QueryCommand.OPTS_OPLOG_REPLAY; - } - } - - if(self.exhaust) { - queryOptions |= QueryCommand.OPTS_EXHAUST; - } - - // Unpack the read preference to set slave ok correctly - var readPreference = self.readPreference instanceof ReadPreference ? self.readPreference.mode : self.readPreference; - - // if(self.read == 'secondary') - if(readPreference == ReadPreference.PRIMARY_PREFERRED - || readPreference == ReadPreference.SECONDARY - || readPreference == ReadPreference.SECONDARY_PREFERRED - || readPreference == ReadPreference.NEAREST) { - queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Override slaveOk from the user - if(self.slaveOk) { - queryOptions |= QueryCommand.OPTS_SLAVE; - } - - if(self.partial) { - queryOptions |= QueryCommand.OPTS_PARTIAL; - } - - // limitValue of -1 is a special case used by Db#eval - var numberToReturn = self.limitValue == -1 ? -1 : limitRequest(self); - - // Check if we need a special selector - if(self.sortValue != null || self.explainValue != null || self.hint != null || self.snapshot != null - || self.returnKey != null || self.maxScan != null || self.min != null || self.max != null - || self.showDiskLoc != null || self.comment != null || typeof self.maxTimeMSValue == 'number') { - - // order by - var orderBy = utils.formattedOrderClause(self.sortValue); - - // Build special selector - var specialSelector = {'$query':self.selector}; - if(orderBy) specialSelector['orderby'] = orderBy; - if(self.hint != null && self.hint.constructor == Object) specialSelector['$hint'] = self.hint; - if(self.snapshot != null) specialSelector['$snapshot'] = self.snapshot; - if(self.returnKey != null) specialSelector['$returnKey'] = self.returnKey; - if(self.maxScan != null) specialSelector['$maxScan'] = self.maxScan; - if(self.min != null) specialSelector['$min'] = self.min; - if(self.max != null) specialSelector['$max'] = self.max; - if(self.showDiskLoc != null) specialSelector['$showDiskLoc'] = self.showDiskLoc; - if(self.comment != null) specialSelector['$comment'] = self.comment; - - // If we are querying the $cmd collection we need to add maxTimeMS as a field - // otherwise for a normal query it's a "special selector" $maxTimeMS - if(typeof self.maxTimeMSValue == 'number' - && self.collectionName.indexOf('.$cmd') != -1) { - specialSelector['maxTimeMS'] = self.maxTimeMSValue; - } else if(typeof self.maxTimeMSValue == 'number' - && self.collectionName.indexOf('.$cmd') == -1) { - specialSelector['$maxTimeMS'] = self.maxTimeMSValue; - } - - // If we have explain set only return a single document with automatic cursor close - if(self.explainValue) { - numberToReturn = (-1)*Math.abs(numberToReturn); - specialSelector['$explain'] = true; - } - - // Return the query - return new QueryCommand(self.db, self.collectionName, queryOptions, self.skipValue, numberToReturn, specialSelector, self.fields); - } else { - return new QueryCommand(self.db, self.collectionName, queryOptions, self.skipValue, numberToReturn, self.selector, self.fields); - } -}; - -/** - * @return {Object} Returns an object containing the sort value of this cursor with - * the proper formatting that can be used internally in this cursor. - * @ignore - * @api private - */ -Cursor.prototype.formattedOrderClause = function() { - return utils.formattedOrderClause(this.sortValue); -}; - -/** - * Converts the value of the sort direction into its equivalent numerical value. - * - * @param sortDirection {String|number} Range of acceptable values: - * 'ascending', 'descending', 'asc', 'desc', 1, -1 - * - * @return {number} The equivalent numerical value - * @throws Error if the given sortDirection is invalid - * @ignore - * @api private - */ -Cursor.prototype.formatSortValue = function(sortDirection) { - return utils.formatSortValue(sortDirection); -}; - -/** - * Gets the next document from the cursor. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object on error while the second parameter will contain a document from the returned result or null if there are no more results. - * @api public - */ -Cursor.prototype.nextObject = function(options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - if(self.state == Cursor.INIT) { - var cmd; - try { - cmd = generateQueryCommand(self); - } catch (err) { - return callback(err, null); - } - - // No need to check the keys - var queryOptions = {exhaust: self.exhaust - , raw:self.raw - , readPreference:self.readPreference - , connection:self.connection - , checkKeys: false}; - - // Execute command - var commandHandler = function(err, result) { - // If on reconnect, the command got given a different connection, switch - // the whole cursor to it. - self.connection = queryOptions.connection; - self.state = Cursor.OPEN; // Adjust the state of the cursor - if(err != null && result == null) return callback(utils.toError(err), null); - - if(err == null && (result == null || result.documents == null || !Array.isArray(result.documents))) { - return self.close(function() {callback(new Error("command failed to return results"), null);}); - } - - if(err == null && result && result.documents[0] && result.documents[0]['$err']) { - return self.close(function() {callback(utils.toError(result.documents[0]), null);}); - } - - if(err == null && result && result.documents[0] && result.documents[0]['errmsg']) { - return self.close(function() {callback(utils.toError(result.documents[0]), null);}); - } - - self.queryRun = true; - self.cursorId = result.cursorId; - self.totalNumberOfRecords = result.numberReturned; - - // Add the new documents to the list of items, using forloop to avoid - // new array allocations and copying - for(var i = 0; i < result.documents.length; i++) { - self.items.push(result.documents[i]); - } - - // If we have noReturn set just return (not modifying the internal item list) - // used for toArray - if(options.noReturn) { - return callback(null, true); - } - - // Ignore callbacks until the cursor is dead for exhausted - if(self.exhaust && result.cursorId.toString() == "0") { - self.nextObject(callback); - } else if(self.exhaust == false || self.exhaust == null) { - self.nextObject(callback); - } - }; - - // If we have no connection set on this cursor check one out - if(self.connection == null) { - try { - self.connection = self.db.serverConfig.checkoutReader(this.readPreference); - - // Check if we have an error from the checkout Reader function - if(self.connection instanceof Error) { - return callback(utils.toError(self.connection), null); - } - - // Add to the query options - queryOptions.connection = self.connection; - } catch(err) { - return callback(utils.toError(err), null); - } - } - - // Execute the command - self.db._executeQueryCommand(cmd, queryOptions, commandHandler); - // Set the command handler to null - commandHandler = null; - } else if(self.items.length) { - var doc = self.items.shift(); - // If we have a transform - if(typeof self.transforms == 'function') { - doc = self.transforms(doc); - } - - callback(null, doc); - } else if(self.cursorId.greaterThan(Long.fromInt(0))) { - getMore(self, callback); - } else { - // Force cursor to stay open - return self.close(function() {callback(null, null);}); - } -} - -/** - * Gets more results from the database if any. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object on error while the second parameter will contain a document from the returned result or null if there are no more results. - * @ignore - * @api private - */ -var getMore = function(self, options, callback) { - var limit = 0; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - if(self.state == Cursor.GET_MORE) return callback(null, null); - - // Set get more in progress - self.state = Cursor.GET_MORE; - - // Set options - if (!self.tailable && self.limitValue > 0) { - limit = self.limitValue - self.totalNumberOfRecords; - if (limit < 1) { - self.close(function() {callback(null, null);}); - return; - } - } - - try { - var getMoreCommand = new GetMoreCommand( - self.db - , self.collectionName - , limitRequest(self) - , self.cursorId - ); - - // Set up options - var command_options = { - readPreference: self.readPreference - , raw: self.raw - , connection:self.connection - }; - - // Execute the command - self.db._executeQueryCommand(getMoreCommand, command_options, function(err, result) { - var cbValue; - - // Get more done - self.state = Cursor.OPEN; - - if(err != null) { - self.state = Cursor.CLOSED; - return callback(utils.toError(err), null); - } - - // Ensure we get a valid result - if(!result || !result.documents) { - self.state = Cursor.CLOSED; - return callback(utils.toError("command failed to return results"), null) - } - - // If we have a timed out query - if((result.responseFlag & (1 << 0)) != 0) { - self.state = Cursor.CLOSED; - return callback(utils.toError("cursor killed or timed out"), null); - } - - // If the QueryFailure flag is set - if((result.responseFlag & (1 << 1)) != 0) { - self.state = Cursor.CLOSED; - return callback(utils.toError("QueryFailure flag set on getmore command"), null); - } - - try { - var isDead = 1 === result.responseFlag && result.cursorId.isZero(); - - self.cursorId = result.cursorId; - self.totalNumberOfRecords += result.numberReturned; - - // Determine if there's more documents to fetch - if(result.numberReturned > 0) { - if (self.limitValue > 0) { - var excessResult = self.totalNumberOfRecords - self.limitValue; - - if (excessResult > 0) { - result.documents.splice(-1 * excessResult, excessResult); - } - } - - // Reset the tries for awaitdata if we are using it - self.currentNumberOfRetries = self.numberOfRetries; - // Get the documents - for(var i = 0; i < result.documents.length; i++) { - self.items.push(result.documents[i]); - } - - // Don's shift a document out as we need it for toArray - if(options.noReturn) { - cbValue = true; - } else { - cbValue = self.items.shift(); - } - } else if(self.tailable && !isDead && self.awaitdata) { - // Excute the tailable cursor once more, will timeout after ~4 sec if awaitdata used - self.currentNumberOfRetries = self.currentNumberOfRetries - 1; - if(self.currentNumberOfRetries == 0) { - self.close(function() { - callback(new Error("tailable cursor timed out"), null); - }); - } else { - getMore(self, callback); - } - } else if(self.tailable && !isDead) { - self.getMoreTimer = setTimeout(function() { getMore(self, callback); }, self.tailableRetryInterval); - } else { - self.close(function() {callback(null, null); }); - } - - result = null; - } catch(err) { - callback(utils.toError(err), null); - } - if (cbValue != null) callback(null, cbValue); - }); - - getMoreCommand = null; - } catch(err) { - // Get more done - self.state = Cursor.OPEN; - - var handleClose = function() { - callback(utils.toError(err), null); - }; - - self.close(handleClose); - handleClose = null; - } -} - -/** - * Gets a detailed information about how the query is performed on this cursor and how - * long it took the database to process it. - * - * @param {Function} callback this will be called after executing this method. The first parameter will always be null while the second parameter will be an object containing the details. - * @api public - */ -Cursor.prototype.explain = function(callback) { - var limit = (-1)*Math.abs(this.limitValue); - - // Create a new cursor and fetch the plan - var cursor = new Cursor(this.db, this.collection, this.selector, this.fields, { - skip: this.skipValue - , limit:limit - , sort: this.sortValue - , hint: this.hint - , explain: true - , snapshot: this.snapshot - , timeout: this.timeout - , tailable: this.tailable - , batchSize: this.batchSizeValue - , slaveOk: this.slaveOk - , raw: this.raw - , readPreference: this.readPreference - , returnKey: this.returnKey - , maxScan: this.maxScan - , min: this.min - , max: this.max - , showDiskLoc: this.showDiskLoc - , comment: this.comment - , awaitdata: this.awaitdata - , oplogReplay: this.oplogReplay - , numberOfRetries: this.numberOfRetries - , dbName: this.dbName - }); - - // Fetch the explaination document - cursor.nextObject(function(err, item) { - if(err != null) return callback(utils.toError(err), null); - // close the cursor - cursor.close(function(err, result) { - if(err != null) return callback(utils.toError(err), null); - callback(null, item); - }); - }); -}; - -/** - * Returns a Node Transform Stream interface for this cursor. - * - * Options - * - **transform** {Function} function of type function(object) { return transformed }, allows for transformation of data before emitting. - * - * @return {CursorStream} returns a stream object. - * @api public - */ -Cursor.prototype.stream = function stream(options) { - return new CursorStream(this, options); -} - -/** - * Close the cursor. - * - * @param {Function} callback this will be called after executing this method. The first parameter will always contain null while the second parameter will contain a reference to this cursor. - * @return {null} - * @api public - */ -Cursor.prototype.close = function(callback) { - var self = this - this.getMoreTimer && clearTimeout(this.getMoreTimer); - // Close the cursor if not needed - if(this.cursorId instanceof Long && this.cursorId.greaterThan(Long.fromInt(0))) { - try { - var command = new KillCursorCommand(this.db, [this.cursorId]); - // Added an empty callback to ensure we don't throw any null exceptions - this.db._executeQueryCommand(command, {readPreference:self.readPreference, raw:self.raw, connection:self.connection}); - } catch(err) {} - } - - // Null out the connection - self.connection = null; - // Reset cursor id - this.cursorId = Long.fromInt(0); - // Set to closed status - this.state = Cursor.CLOSED; - - if(callback) { - callback(null, self); - self.items = []; - } - - return this; -}; - -/** - * Check if the cursor is closed or open. - * - * @return {Boolean} returns the state of the cursor. - * @api public - */ -Cursor.prototype.isClosed = function() { - return this.state == Cursor.CLOSED ? true : false; -}; - -/** - * Init state - * - * @classconstant INIT - **/ -Cursor.INIT = 0; - -/** - * Cursor open - * - * @classconstant OPEN - **/ -Cursor.OPEN = 1; - -/** - * Cursor closed - * - * @classconstant CLOSED - **/ -Cursor.CLOSED = 2; - -/** - * Cursor performing a get more - * - * @classconstant OPEN - **/ -Cursor.GET_MORE = 3; - -/** - * @ignore - * @api private - */ -exports.Cursor = Cursor; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/cursorstream.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/cursorstream.js deleted file mode 100755 index 4370f45e..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/cursorstream.js +++ /dev/null @@ -1,167 +0,0 @@ -var timers = require('timers'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('./utils').processor(); - -/** - * Module dependecies. - */ -var Stream = require('stream').Stream; - -/** - * CursorStream - * - * Returns a stream interface for the **cursor**. - * - * Options - * - **transform** {Function} function of type function(object) { return transformed }, allows for transformation of data before emitting. - * - * Events - * - **data** {function(item) {}} the data event triggers when a document is ready. - * - **error** {function(err) {}} the error event triggers if an error happens. - * - **close** {function() {}} the end event triggers when there is no more documents available. - * - * @class Represents a CursorStream. - * @param {Cursor} cursor a cursor object that the stream wraps. - * @return {Stream} - */ -function CursorStream(cursor, options) { - if(!(this instanceof CursorStream)) return new CursorStream(cursor); - options = options ? options : {}; - - Stream.call(this); - - this.readable = true; - this.paused = false; - this._cursor = cursor; - this._destroyed = null; - this.options = options; - - // give time to hook up events - var self = this; - process.nextTick(function() { - self._init(); - }); -} - -/** - * Inherit from Stream - * @ignore - * @api private - */ -CursorStream.prototype.__proto__ = Stream.prototype; - -/** - * Flag stating whether or not this stream is readable. - */ -CursorStream.prototype.readable; - -/** - * Flag stating whether or not this stream is paused. - */ -CursorStream.prototype.paused; - -/** - * Initialize the cursor. - * @ignore - * @api private - */ -CursorStream.prototype._init = function () { - if (this._destroyed) return; - this._next(); -} - -/** - * Pull the next document from the cursor. - * @ignore - * @api private - */ -CursorStream.prototype._next = function () { - if(this.paused || this._destroyed) return; - - var self = this; - // Get the next object - processor(function() { - if(self.paused || self._destroyed) return; - - self._cursor.nextObject(function (err, doc) { - self._onNextObject(err, doc); - }); - }); -} - -/** - * Handle each document as its returned from the cursor. - * @ignore - * @api private - */ -CursorStream.prototype._onNextObject = function (err, doc) { - if(err) { - this.destroy(err); - return this.emit('end'); - } - - // when doc is null we hit the end of the cursor - if(!doc && (this._cursor.state == 1 || this._cursor.state == 2)) { - this.emit('end') - return this.destroy(); - } else if(doc) { - var data = typeof this.options.transform == 'function' ? this.options.transform(doc) : doc; - this.emit('data', data); - this._next(); - } -} - -/** - * Pauses the stream. - * - * @api public - */ -CursorStream.prototype.pause = function () { - this.paused = true; -} - -/** - * Resumes the stream. - * - * @api public - */ -CursorStream.prototype.resume = function () { - var self = this; - - // Don't do anything if we are not paused - if(!this.paused) return; - if(!this._cursor.state == 3) return; - - process.nextTick(function() { - self.paused = false; - // Only trigger more fetching if the cursor is open - self._next(); - }) -} - -/** - * Destroys the stream, closing the underlying - * cursor. No more events will be emitted. - * - * @api public - */ -CursorStream.prototype.destroy = function (err) { - if (this._destroyed) return; - this._destroyed = true; - this.readable = false; - - this._cursor.close(); - - if(err && this.listeners('error').length > 0) { - return this.emit('error', err); - } - - this.emit('close'); -} - -// TODO - maybe implement the raw option to pass binary? -//CursorStream.prototype.setEncoding = function () { -//} - -module.exports = exports = CursorStream; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/db.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/db.js deleted file mode 100755 index c7c4bf38..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/db.js +++ /dev/null @@ -1,2182 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -var QueryCommand = require('./commands/query_command').QueryCommand - , DbCommand = require('./commands/db_command').DbCommand - , MongoReply = require('./responses/mongo_reply').MongoReply - , Admin = require('./admin').Admin - , Collection = require('./collection').Collection - , Server = require('./connection/server').Server - , ReplSet = require('./connection/repl_set/repl_set').ReplSet - , ReadPreference = require('./connection/read_preference').ReadPreference - , Mongos = require('./connection/mongos').Mongos - , Cursor = require('./cursor').Cursor - , EventEmitter = require('events').EventEmitter - , InsertCommand = require('./commands/insert_command').InsertCommand - , CommandCursor = require('./command_cursor').CommandCursor - , f = require('util').format - , inherits = require('util').inherits - , crypto = require('crypto') - , timers = require('timers') - , utils = require('./utils') - - // Authentication methods - , mongodb_cr_authenticate = require('./auth/mongodb_cr.js').authenticate - , mongodb_gssapi_authenticate = require('./auth/mongodb_gssapi.js').authenticate - , mongodb_sspi_authenticate = require('./auth/mongodb_sspi.js').authenticate - , mongodb_plain_authenticate = require('./auth/mongodb_plain.js').authenticate - , mongodb_x509_authenticate = require('./auth/mongodb_x509.js').authenticate - , mongodb_scram_authenticate = require('./auth/mongodb_scram.js').authenticate; - -var hasKerberos = false; -// Check if we have a the kerberos library -try { - require('kerberos'); - hasKerberos = true; -} catch(err) {} - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('./utils').processor(); - -/** - * Create a new Db instance. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **native_parser** {Boolean, default:false}, use c++ bson parser. - * - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **serializeFunctions** {Boolean, default:false}, serialize functions. - * - **raw** {Boolean, default:false}, perform operations using raw bson buffers. - * - **recordQueryStats** {Boolean, default:false}, record query statistics during execution. - * - **retryMiliSeconds** {Number, default:5000}, number of milliseconds between retries. - * - **numberOfRetries** {Number, default:5}, number of retries off connection. - * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**. - * - **slaveOk** {Number, default:null}, force setting of SlaveOk flag on queries (only use when explicitly connecting to a secondary server). - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - **bufferMaxEntries** {Number, default: -1}, sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * - * @class Represents a Db - * @param {String} databaseName name of the database. - * @param {Object} serverConfig server config object. - * @param {Object} [options] additional options for the collection. - */ -function Db(databaseName, serverConfig, options) { - if(!(this instanceof Db)) return new Db(databaseName, serverConfig, options); - EventEmitter.call(this); - var self = this; - this.databaseName = databaseName; - this.serverConfig = serverConfig; - this.options = options == null ? {} : options; - // State to check against if the user force closed db - this._applicationClosed = false; - // Fetch the override flag if any - var overrideUsedFlag = this.options['override_used_flag'] == null ? false : this.options['override_used_flag']; - - // Verify that nobody is using this config - if(!overrideUsedFlag && this.serverConfig != null && typeof this.serverConfig == 'object' && this.serverConfig._isUsed && this.serverConfig._isUsed()) { - throw new Error('A Server or ReplSet instance cannot be shared across multiple Db instances'); - } else if(!overrideUsedFlag && typeof this.serverConfig == 'object'){ - // Set being used - this.serverConfig._used = true; - } - - // Allow slaveOk override - this.slaveOk = this.options['slave_ok'] == null ? false : this.options['slave_ok']; - this.slaveOk = this.options['slaveOk'] == null ? this.slaveOk : this.options['slaveOk']; - - // Number of operations to buffer before failure - this.bufferMaxEntries = typeof this.options['bufferMaxEntries'] == 'number' ? this.options['bufferMaxEntries'] : -1; - - // Ensure we have a valid db name - validateDatabaseName(databaseName); - - // Contains all the connections for the db - try { - this.native_parser = this.options.native_parser; - // The bson lib - var bsonLib = this.bsonLib = this.options.native_parser ? require('bson').BSONNative : require('bson').BSONPure; - bsonLib = require('bson').BSONPure; - // Fetch the serializer object - var BSON = bsonLib.BSON; - - // Create a new instance - this.bson = new BSON([bsonLib.Long, bsonLib.ObjectID, bsonLib.Binary, bsonLib.Code, bsonLib.DBRef, bsonLib.Symbol, bsonLib.Double, bsonLib.Timestamp, bsonLib.MaxKey, bsonLib.MinKey]); - this.bson.promoteLongs = this.options.promoteLongs == null ? true : this.options.promoteLongs; - - // Backward compatibility to access types - this.bson_deserializer = bsonLib; - this.bson_serializer = bsonLib; - - // Add any overrides to the serializer and deserializer - this.bson_deserializer.promoteLongs = this.options.promoteLongs == null ? true : this.options.promoteLongs; - } catch (err) { - // If we tried to instantiate the native driver - var msg = 'Native bson parser not compiled, please compile ' - + 'or avoid using native_parser=true'; - throw Error(msg); - } - - // Internal state of the server - this._state = 'disconnected'; - - this.pkFactory = this.options.pkFactory == null ? bsonLib.ObjectID : this.options.pkFactory; - this.forceServerObjectId = this.options.forceServerObjectId != null ? this.options.forceServerObjectId : false; - - // Added safe - this.safe = this.options.safe == null ? false : this.options.safe; - - // If we have not specified a "safe mode" we just print a warning to the console - if(this.options.safe == null - && this.options.w == null - && this.options.j == null - && this.options.journal == null - && this.options.fsync == null) { - console.log("========================================================================================"); - console.log("= Please ensure that you set the default write concern for the database by setting ="); - console.log("= one of the options ="); - console.log("= ="); - console.log("= w: (value of > -1 or the string 'majority'), where < 1 means ="); - console.log("= no write acknowledgement ="); - console.log("= journal: true/false, wait for flush to journal before acknowledgement ="); - console.log("= fsync: true/false, wait for flush to file system before acknowledgement ="); - console.log("= ="); - console.log("= For backward compatibility safe is still supported and ="); - console.log("= allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] ="); - console.log("= the default value is false which means the driver receives does not ="); - console.log("= return the information of the success/error of the insert/update/remove ="); - console.log("= ="); - console.log("= ex: new Db(new Server('localhost', 27017), {safe:false}) ="); - console.log("= ="); - console.log("= http://www.mongodb.org/display/DOCS/getLastError+Command ="); - console.log("= ="); - console.log("= The default of no acknowledgement will change in the very near future ="); - console.log("= ="); - console.log("= This message will disappear when the default safe is set on the driver Db ="); - console.log("========================================================================================"); - } - - // Internal states variables - this.notReplied ={}; - this.isInitializing = true; - this.openCalled = false; - - // Command queue, keeps a list of incoming commands that need to be executed once the connection is up - this.commands = []; - - // Set up logger - this.logger = this.options.logger != null - && (typeof this.options.logger.debug == 'function') - && (typeof this.options.logger.error == 'function') - && (typeof this.options.logger.log == 'function') - ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}; - - // Associate the logger with the server config - this.serverConfig.logger = this.logger; - if(this.serverConfig.strategyInstance) this.serverConfig.strategyInstance.logger = this.logger; - this.tag = new Date().getTime(); - // Just keeps list of events we allow - this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[]}; - - // Controls serialization options - this.serializeFunctions = this.options.serializeFunctions != null ? this.options.serializeFunctions : false; - - // Raw mode - this.raw = this.options.raw != null ? this.options.raw : false; - - // Record query stats - this.recordQueryStats = this.options.recordQueryStats != null ? this.options.recordQueryStats : false; - - // If we have server stats let's make sure the driver objects have it enabled - if(this.recordQueryStats == true) { - this.serverConfig.enableRecordQueryStats(true); - } - - // Retry information - this.retryMiliSeconds = this.options.retryMiliSeconds != null ? this.options.retryMiliSeconds : 1000; - this.numberOfRetries = this.options.numberOfRetries != null ? this.options.numberOfRetries : 60; - - // Set default read preference if any - this.readPreference = this.options.readPreference; - - // Set slaveOk if we have specified a secondary or secondary preferred readPreference - if(this.readPreference == ReadPreference.SECONDARY || - this.readPreference == ReadPreference.SECONDARY_PREFERRED) { - this.slaveOk = true; - } - - // Set read preference on serverConfig if none is set - // but the db one was - if(this.serverConfig.options.readPreference != null) { - this.serverConfig.setReadPreference(this.serverConfig.options.readPreference); - } else if(this.readPreference != null) { - this.serverConfig.setReadPreference(this.readPreference); - } - - // Ensure we keep a reference to this db - this.serverConfig._dbStore.add(this); -}; - -/** - * @ignore - */ -function validateDatabaseName(databaseName) { - if(typeof databaseName !== 'string') throw new Error("database name must be a string"); - if(databaseName.length === 0) throw new Error("database name cannot be the empty string"); - if(databaseName == '$external') return; - - var invalidChars = [" ", ".", "$", "/", "\\"]; - for(var i = 0; i < invalidChars.length; i++) { - if(databaseName.indexOf(invalidChars[i]) != -1) throw new Error("database names cannot contain the character '" + invalidChars[i] + "'"); - } -} - -/** - * @ignore - */ -inherits(Db, EventEmitter); - -/** - * Initialize the database connection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the index information or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.open = function(callback) { - var self = this; - - // Check that the user has not called this twice - if(this.openCalled) { - // Close db - this.close(); - // Throw error - throw new Error("db object already connecting, open cannot be called multiple times"); - } - - // If we have a specified read preference - if(this.readPreference != null) this.serverConfig.setReadPreference(this.readPreference); - - // Set that db has been opened - this.openCalled = true; - - // Set the status of the server - self._state = 'connecting'; - - // Set up connections - if(self.serverConfig instanceof Server || self.serverConfig instanceof ReplSet || self.serverConfig instanceof Mongos) { - // Ensure we have the original options passed in for the server config - var connect_options = {}; - for(var name in self.serverConfig.options) { - connect_options[name] = self.serverConfig.options[name] - } - connect_options.firstCall = true; - - // Attempt to connect - self.serverConfig.connect(self, connect_options, function(err, result) { - if(err != null) { - // Close db to reset connection - return self.close(function () { - // Return error from connection - return callback(err, null); - }); - } - // Set the status of the server - self._state = 'connected'; - // If we have queued up commands execute a command to trigger replays - if(self.commands.length > 0) _execute_queued_command(self); - // Callback - process.nextTick(function() { - try { - callback(null, self); - } catch(err) { - self.close(); - throw err; - } - }); - }); - } else { - try { - callback(Error("Server parameter must be of type Server, ReplSet or Mongos"), null); - } catch(err) { - self.close(); - throw err; - } - } -}; - -/** - * Create a new Db instance sharing the current socket connections. - * - * @param {String} dbName the name of the database we want to use. - * @return {Db} a db instance using the new database. - * @api public - */ -Db.prototype.db = function(dbName) { - // Copy the options and add out internal override of the not shared flag - var options = {}; - for(var key in this.options) { - options[key] = this.options[key]; - } - - // Add override flag - options['override_used_flag'] = true; - // Check if the db already exists and reuse if it's the case - var db = this.serverConfig._dbStore.fetch(dbName); - - // Create a new instance - if(!db) { - db = new Db(dbName, this.serverConfig, options); - } - - // Return the db object - return db; -}; - -/** - * Close the current db connection, including all the child db instances. Emits close event and calls optional callback. - * - * @param {Boolean} [forceClose] connection can never be reused. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.close = function(forceClose, callback) { - var self = this; - // Ensure we force close all connections - this._applicationClosed = false; - - if(typeof forceClose == 'function') { - callback = forceClose; - } else if(typeof forceClose == 'boolean') { - this._applicationClosed = forceClose; - } - - this.serverConfig.close(function(err, result) { - // You can reuse the db as everything is shut down - self.openCalled = false; - // If we have a callback call it - if(callback) callback(err, result); - }); -}; - -/** - * Access the Admin database - * - * @param {Function} [callback] returns the results. - * @return {Admin} the admin db object. - * @api public - */ -Db.prototype.admin = function(callback) { - if(callback == null) return new Admin(this); - callback(null, new Admin(this)); -}; - -var transformCollections = function(databaseName) { - var matching = f('%s.', databaseName); - - return function(results) { - if(Array.isArray(results)) { - for(var i = 0; i < results.length; i++) { - var index = results[i].name.indexOf(matching); - // Remove database name if available - if(results[i].name && index == 0) { - results[i].name = results[i].name.substr(index + matching.length); - } - } - } else { - var index = results.name.indexOf(matching); - if(index == 0) { - results.name = results.name.substr(index + matching.length); - } - } - - // Return the results - return results; - } -} - -/** - * Get the list of all collection names for the specified db - * - * Options - * - **batchSize** {Number, default:null}, The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * - * @param {object} filter Query to filter collections by - * @param {object} [options] additional options during update. - * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @return {Cursor} - * @api public - */ -Db.prototype.listCollections = function(filter, options) { - filter = filter || {}; - options = options || {}; - - // Checkout the writer - var connection = this.serverConfig.checkoutReader(); - // We have a list collections command - if(connection && connection.serverCapabilities.hasListCollectionsCommand) { - // Cursor options - var cursor = options.batchSize ? {batchSize: options.batchSize} : {} - // Build the command - var command = { listCollections : true, filter: filter, cursor: cursor }; - // Get the command cursor - return new CommandCursor(this, this.collection(DbCommand.SYSTEM_NAMESPACE_COLLECTION), command, {transform: transformCollections(this.databaseName) }); - } - - // We cannot use the listCollectionsCommand - if(connection && !connection.serverCapabilities.hasListCollectionsCommand) { - // If we have legacy mode and have not provided a full db name filter it - // Use Regex to correctly check if the filter name contains the database name at the beginning along with a dot - if(typeof filter.name == 'string' && !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) { - filter = utils.shallowObjectCopy(filter); - filter.name = f('%s.%s', this.databaseName, filter.name); - } - } - - // No filter, filter by current database - if(filter == null) { - filter.name = f('/%s/', this.databaseName); - } - - // Rewrite the filter to use $and to filter out indexes - if(filter.name) { - filter = {$and: [{name: filter.name}, {name:/^((?!\$).)*$/}]}; - } else { - filter = {name:/^((?!\$).)*$/}; - } - - // Return options - var options = {transforms: transformCollections(this.databaseName)} - // Get the cursor - var cursor = this.collection(DbCommand.SYSTEM_NAMESPACE_COLLECTION).find(filter, options); - // Set the passed in batch size if one was provided - if(options.batchSize) cursor = cursor.batchSize(options.batchSize); - // We have a fallback mode using legacy systems collections - return cursor; -}; - -/** - * Get the list of all collection names for the specified db - * - * Options - * - **namesOnly** {String, default:false}, Return only the full collection namespace. - * - * @param {String} [collectionName] the collection name we wish to filter by. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collection names or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.collectionNames = function(collectionName, options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - collectionName = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - var filter = {} - if(collectionName) { - filter.name = collectionName; - } - - // Call list collections - this.listCollections(filter, options).toArray(callback); -}; - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can - * can use it without a callback in the following way. var collection = db.collection('mycollection'); - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **raw** {Boolean, default:false}, perform all operations using raw bson objects. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **strict**, (Boolean, default:false) returns an error if the collection does not exist - * - * @param {String} collectionName the collection name we wish to access. - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collection or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.collection = function(collectionName, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - var self = this; - - if(options == null || !options.strict) { - try { - var collection = new Collection(self, collectionName, self.pkFactory, options); - if(callback) callback(null, collection); - return collection; - } catch(err) { - if(callback) return callback(err); - throw err; - } - } - - // Strict mode - if(typeof callback != 'function') { - throw utils.toError(f("A callback is required in strict mode. While getting collection %s.", collectionName)); - } - - self.listCollections({name:collectionName}).toArray(function(err, collections) { - if(err != null) return callback(err, null); - if(collections.length == 0) return callback(utils.toError(f("Collection %s does not exist. Currently in strict mode.", collectionName)), null); - - try { - return callback(null, new Collection(self, collectionName, self.pkFactory, options)); - } catch(err) { - return callback(err, null); - } - }); -}; - -/** - * Fetch all collections for the current db. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collections or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.collections = function(callback) { - var self = this; - // Let's get the collection names - self.collectionNames(function(err, documents) { - if(err != null) return callback(err, null); - - // Filter collections removing any illegal ones - documents = documents.filter(function(doc) { - return doc.name.indexOf('$') == -1; - }); - - // Create collection objects - var collections = documents.map(function(document) { - return new Collection(self, document.name.replace(self.databaseName + ".", ''), self.pkFactory); - }); - - // Return the collection objects - callback(null, collections); - }); -}; - -/** - * Evaluate javascript on the server - * - * Options - * - **nolock** {Boolean, default:false}, Tell MongoDB not to block on the evaulation of the javascript. - * - * @param {Code} code javascript to execute on server. - * @param {Object|Array} [parameters] the parameters for the call. - * @param {Object} [options] the options - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from eval or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.eval = function(code, parameters, options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - var finalCode = code; - var finalParameters = []; - // If not a code object translate to one - if(!(finalCode instanceof this.bsonLib.Code)) { - finalCode = new this.bsonLib.Code(finalCode); - } - - // Ensure the parameters are correct - if(parameters != null && parameters.constructor != Array && typeof parameters !== 'function') { - finalParameters = [parameters]; - } else if(parameters != null && parameters.constructor == Array && typeof parameters !== 'function') { - finalParameters = parameters; - } - - // Create execution selector - var cmd = {'$eval':finalCode, 'args':finalParameters}; - // Check if the nolock parameter is passed in - if(options['nolock']) { - cmd['nolock'] = options['nolock']; - } - - // Set primary read preference - options.readPreference = ReadPreference.PRIMARY; - - // Execute the command - this.command(cmd, options, function(err, result) { - if(err) return callback(err, null); - if(result && result.ok == 1) return callback(null, result.retval); - if(result) return callback(new Error("eval failed: " + result.errmsg), null); - callback(err, result); - }); -}; - -/** - * Dereference a dbref, against a db - * - * @param {DBRef} dbRef db reference object we wish to resolve. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dereference or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.dereference = function(dbRef, callback) { - var db = this; - // If we have a db reference then let's get the db first - if(dbRef.db != null) db = this.db(dbRef.db); - // Fetch the collection and find the reference - var collection = db.collection(dbRef.namespace); - collection.findOne({'_id':dbRef.oid}, function(err, result) { - callback(err, result); - }); -} - -/** - * Logout user from server, fire off on all connections and remove all auth info - * - * Options - * - **authMechanism** {String, default:MONGODB-CR}, The authentication mechanism to use, GSSAPI or MONGODB-CR - * - **authdb** {String}, The Db to authenticate against instead of this - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from logout or null if an error occurred. - * @param {Object} [options] the options - * @return {null} - * @api public - */ -Db.prototype.logout = function(options, callback) { - var self = this; - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // We have passed in an auth db - var runDb = options.authdb ? this.db(options.authdb) : this; - - // Number of connections we need to logout from - var numberOfConnections = this.serverConfig.allRawConnections().length; - // logout command - var cmd = {'logout':1}; - // Add onAll to login to ensure all connection are logged out - options.onAll = true; - - // Execute the command - runDb.command(cmd, options, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - // Work around the case where the number of connections are 0 - if(numberOfConnections == 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - // Remove the db from auths - self.serverConfig.auth.remove(self.databaseName); - // Callback with result - internalCallback(null, result.ok == 1 ? true : false); - } - }); -} - -/** - * Authenticate a user against the server. - * authMechanism - * Options - * - **authMechanism** {String, default:MONGODB-CR}, The authentication mechanism to use, GSSAPI or MONGODB-CR - * - **authdb** {String}, The Db to authenticate against instead of this - * - * @param {String} username username. - * @param {String} password password. - * @param {Object} [options] the options - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from authentication or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.authenticate = function(username, password, options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {}; - } else { - options = utils.shallowObjectCopy(options); - } - - // Set default mechanism - if(!options.authMechanism) { - options.authMechanism = 'DEFAULT'; - } else if(options.authMechanism != 'GSSAPI' - && options.authMechanism != 'MONGODB-CR' - && options.authMechanism != 'MONGODB-X509' - && options.authMechanism != 'SCRAM-SHA-1' - && options.authMechanism != 'PLAIN') { - return callback(new Error("only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism")); - } - - // the default db to authenticate against is 'this' - // if authententicate is called from a retry context, it may be another one, like admin - var authdb = options.authdb ? options.authdb : self.databaseName; - authdb = options.authSource ? options.authSource : authdb; - - // Callback - var _callback = function(err, result) { - if(self.listeners("authenticated").length > 0) { - self.emit("authenticated", err, result); - } - - // Return to caller - callback(err, result); - } - - // If classic auth delegate to auth command - if(options.authMechanism == 'MONGODB-CR') { - mongodb_cr_authenticate(self, username, password, authdb, options, _callback); - } else if(options.authMechanism == 'PLAIN') { - mongodb_plain_authenticate(self, username, password, options, _callback); - } else if(options.authMechanism == 'MONGODB-X509') { - mongodb_x509_authenticate(self, username, password, options, _callback); - } else if(options.authMechanism == 'SCRAM-SHA-1') { - mongodb_scram_authenticate(self, username, password, authdb, options, _callback); - } else if(options.authMechanism == 'DEFAULT') { - // Get a server - var servers = this.serverConfig.allServerInstances(); - // if the max wire protocol version >= 3 do scram otherwise mongodb_cr - if(servers.length > 0 && servers[0].isMasterDoc && servers[0].isMasterDoc.maxWireVersion >= 3) { - mongodb_scram_authenticate(self, username, password, authdb, options, _callback); - } else { - mongodb_cr_authenticate(self, username, password, authdb, options, _callback); - } - } else if(options.authMechanism == 'GSSAPI') { - // - // Kerberos library is not installed, throw and error - if(hasKerberos == false) { - console.log("========================================================================================"); - console.log("= Please make sure that you install the Kerberos library to use GSSAPI ="); - console.log("= ="); - console.log("= npm install -g kerberos ="); - console.log("= ="); - console.log("= The Kerberos package is not installed by default for simplicities sake ="); - console.log("= and needs to be global install ="); - console.log("========================================================================================"); - throw new Error("Kerberos library not installed"); - } - - if(process.platform == 'win32') { - mongodb_sspi_authenticate(self, username, password, authdb, options, _callback); - } else { - // We have the kerberos library, execute auth process - mongodb_gssapi_authenticate(self, username, password, authdb, options, _callback); - } - } -}; - -/** - * Add a user to the database. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **customData**, (Object, default:{}) custom data associated with the user (only Mongodb 2.6 or higher) - * - **roles**, (Array, default:[]) roles associated with the created user (only Mongodb 2.6 or higher) - * - * @param {String} username username. - * @param {String} password password. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from addUser or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.addUser = function(username, password, options, callback) { - // Checkout a write connection to get the server capabilities - var connection = this.serverConfig.checkoutWriter(); - if(connection != null - && connection.serverCapabilities != null - && connection.serverCapabilities.hasAuthCommands) { - return _executeAuthCreateUserCommand(this, username, password, options, callback); - } - - // Unpack the parameters - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // Get the error options - var errorOptions = _getWriteConcern(this, options); - errorOptions.w = errorOptions.w == null ? 1 : errorOptions.w; - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var userPassword = md5.digest('hex'); - // Fetch a user collection - var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION); - // Check if we are inserting the first user - collection.count({}, function(err, count) { - // We got an error (f.ex not authorized) - if(err != null) return callback(err, null); - // Check if the user exists and update i - collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) { - // We got an error (f.ex not authorized) - if(err != null) return callback(err, null); - // Add command keys - var commandOptions = errorOptions; - commandOptions.dbName = options['dbName']; - commandOptions.upsert = true; - - // We have a user, let's update the password or upsert if not - collection.update({user: username},{$set: {user: username, pwd: userPassword}}, commandOptions, function(err, results, full) { - if(count == 0 && err) { - callback(null, [{user:username, pwd:userPassword}]); - } else if(err) { - callback(err, null) - } else { - callback(null, [{user:username, pwd:userPassword}]); - } - }); - }); - }); -}; - -/** - * @ignore - */ -var _executeAuthCreateUserCommand = function(self, username, password, options, callback) { - // Special case where there is no password ($external users) - if(typeof username == 'string' - && password != null && typeof password == 'object') { - callback = options; - options = password; - password = null; - } - - // Unpack all options - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Error out if we digestPassword set - if(options.digestPassword != null) { - throw utils.toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."); - } - - // Get additional values - var customData = options.customData != null ? options.customData : {}; - var roles = Array.isArray(options.roles) ? options.roles : []; - var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; - - // If not roles defined print deprecated message - if(roles.length == 0) { - console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"); - } - - // Get the error options - var writeConcern = _getWriteConcern(self, options); - var commandOptions = {writeCommand:true}; - if(options['dbName']) commandOptions.dbName = options['dbName']; - - // Add maxTimeMS to options if set - if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Check the db name and add roles if needed - if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') && !Array.isArray(options.roles)) { - roles = ['root'] - } else if(!Array.isArray(options.roles)) { - roles = ['dbOwner'] - } - - // Build the command to execute - var command = { - createUser: username - , customData: customData - , roles: roles - , digestPassword:false - , writeConcern: writeConcern - } - - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var userPassword = md5.digest('hex'); - - // No password - if(typeof password == 'string') { - command.pwd = userPassword; - } - - // Execute the command - self.command(command, commandOptions, function(err, result) { - if(err) return callback(err, null); - callback(!result.ok ? utils.toError("Failed to add user " + username) : null - , result.ok ? [{user: username, pwd: ''}] : null); - }) -} - -/** - * Remove a user from a database - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - * @param {String} username username. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.removeUser = function(username, options, callback) { - // Checkout a write connection to get the server capabilities - var connection = this.serverConfig.checkoutWriter(); - if(connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasAuthCommands) { - return _executeAuthRemoveUserCommand(this, username, options, callback); - } - - // Unpack the parameters - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // Figure out the safe mode settings - var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe; - // Override with options passed in if applicable - safe = options != null && options['safe'] != null ? options['safe'] : safe; - // Ensure it's at least set to safe - safe = safe == null ? {w: 1} : safe; - - // Fetch a user collection - var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION); - collection.findOne({user: username}, {dbName: options['dbName']}, function(err, user) { - if(user != null) { - // Add command keys - var commandOptions = safe; - commandOptions.dbName = options['dbName']; - - collection.remove({user: username}, commandOptions, function(err, result) { - callback(err, true); - }); - } else { - callback(err, false); - } - }); -}; - -var _executeAuthRemoveUserCommand = function(self, username, options, callback) { - // Unpack all options - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Get the error options - var writeConcern = _getWriteConcern(self, options); - var commandOptions = {writeCommand:true}; - if(options['dbName']) commandOptions.dbName = options['dbName']; - - // Get additional values - var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; - - // Add maxTimeMS to options if set - if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Build the command to execute - var command = { - dropUser: username - , writeConcern: writeConcern - } - - // Execute the command - self.command(command, commandOptions, function(err, result) { - if(err) return callback(err, null); - callback(null, result.ok ? true : false); - }) -} - -/** - * Creates a collection on a server pre-allocating space, need to create f.ex capped collections. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **raw** {Boolean, default:false}, perform all operations using raw bson objects. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **capped** {Boolean, default:false}, create a capped collection. - * - **size** {Number}, the size of the capped collection in bytes. - * - **max** {Number}, the maximum number of documents in the capped collection. - * - **autoIndexId** {Boolean, default:true}, create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2. - * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **strict**, (Boolean, default:false) throws an error if collection already exists - * - * @param {String} collectionName the collection name we wish to access. - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from createCollection or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.createCollection = function(collectionName, options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Figure out the safe mode settings - var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe; - // Override with options passed in if applicable - safe = options != null && options['safe'] != null ? options['safe'] : safe; - // Ensure it's at least set to safe - safe = safe == null ? {w: 1} : safe; - // Check if we have the name - this.listCollections({name:collectionName}).toArray(function(err, collections) { - if(err != null) return callback(err, null); - if(collections.length > 0 && options.strict) { - return callback(utils.toError(f("Collection %s already exists. Currently in strict mode.", collectionName)), null); - } else if (collections.length > 0) { - try { return callback(null, new Collection(self, collectionName, self.pkFactory, options)); } - catch(err) { return callback(err); } - } - - // logout command - var cmd = {'create':collectionName}; - - for(var name in options) { - if(options[name] != null && typeof options[name] != 'function') cmd[name] = options[name]; - } - - // Execute the command - self.command(cmd, options, function(err, result) { - // Handle errors of pre-existing collections - if(err && options && options.strict) { - return callback(err, null); - } - // Attempt to return a collection - try { - callback(null, new Collection(self, collectionName, self.pkFactory, options)); - } catch(err) { - callback(utils.toError(err), null); - } - }); - }); -}; - -var _getReadConcern = function(self, options) { - if(options.readPreference) return options.readPreference; - if(self.readPreference) return self.readPreference; - return 'primary'; -} - -/** - * Execute a command hash against MongoDB. This lets you acess any commands not available through the api on the server. - * - * Options - * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **maxTimeMS** {Number}, number of milliseconds to wait before aborting the query. - * - **ignoreCommandFilter** {Boolean}, overrides the default redirection of certain commands to primary. - * - **writeCommand** {Boolean, default: false}, signals this is a write command and to ignore read preferences - * - **checkKeys** {Boolean, default: false}, overrides the default not to check the key names for the command - * - * @param {Object} selector the command hash to send to the server, ex: {ping:1}. - * @param {Object} [options] additional options for the command. - * @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter. - * @return {null} - * @api public - */ -Db.prototype.command = function(selector, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Make a shallow copy so no modifications happen on the original - options = utils.shallowObjectCopy(options); - - // Ignore command preference (I know what I'm doing) - var ignoreCommandFilter = options.ignoreCommandFilter ? options.ignoreCommandFilter : false; - - // Get read preference if we set one - var readPreference = _getReadConcern(this, options); - - // Ensure only commands who support read Prefrences are exeuted otherwise override and use Primary - if(readPreference != false && ignoreCommandFilter == false) { - if(selector['group'] || selector['aggregate'] || selector['collStats'] || selector['dbStats'] - || selector['count'] || selector['distinct'] || selector['geoNear'] || selector['geoSearch'] - || selector['geoWalk'] || selector['text'] || selector['cursorInfo'] - || selector['parallelCollectionScan'] - || (selector['mapreduce'] && (selector.out == 'inline' || selector.out.inline))) { - // Set the read preference - options.readPreference = readPreference; - } else { - options.readPreference = ReadPreference.PRIMARY; - } - } else if(readPreference != false) { - options.readPreference = readPreference; - } - - // Add the maxTimeMS option to the command if specified - if(typeof options.maxTimeMS == 'number') { - selector.maxTimeMS = options.maxTimeMS - } - - // Command options - var command_options = {}; - - // Do we have an override for checkKeys - if(typeof options['checkKeys'] == 'boolean') command_options['checkKeys'] = options['checkKeys']; - command_options['checkKeys'] = typeof options['checkKeys'] == 'boolean' ? options['checkKeys'] : false; - if(typeof options['serializeFunctions'] == 'boolean') command_options['serializeFunctions'] = options['serializeFunctions']; - if(options['dbName']) command_options['dbName'] = options['dbName']; - - // If we have a write command, remove readPreference as an option - if((options.writeCommand - || selector['findAndModify'] - || selector['insert'] || selector['update'] || selector['delete'] - || selector['createUser'] || selector['updateUser'] || selector['removeUser']) - && options.readPreference) { - delete options['readPreference']; - } - - // Add a write concern if we have passed in any - if(options.w || options.wtimeout || options.j || options.fsync || options.safe) { - selector.writeConcern = {}; - if(options.safe) selector.writeConcern.w = 1; - if(options.w) selector.writeConcern.w = options.w; - if(options.wtimeout) selector.writeConcern.wtimeout = options.wtimeout; - if(options.j) selector.writeConcern.j = options.j; - if(options.fsync) selector.writeConcern.fsync = options.fsync; - } - - // If we have an actual writeConcern object override - if(options.writeConcern) { - selector.writeConcern = writeConcern; - } - - // Check if we need to set slaveOk - if(command_options.readPreference != 'primary') - command_options.slaveOk = true; - - // Execution db - var execDb = typeof options.auth == 'string' ? this.db(options.auth) : this; - execDb = typeof options.authdb == 'string' ? this.db(options.authdb) : execDb; - - // Execute a query command - this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(execDb, selector, command_options), options, function(err, results, connection) { - if(options.returnConnection) { - if(err) return callback(err, null, connection); - if(results == null || results.documents == null) return callback(new Error("command failed to return result")); - if(results.documents[0].errmsg) - return callback(utils.toError(results.documents[0]), null, connection); - callback(null, results.documents[0], connection); - } else { - if(err) return callback(err, null); - if(results == null || results.documents == null) return callback(new Error("command failed to return result")); - if(results.documents[0].errmsg) - return callback(utils.toError(results.documents[0]), null); - callback(null, results.documents[0]); - } - }); -}; - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @param {String} collectionName the name of the collection we wish to drop. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dropCollection or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.dropCollection = function(collectionName, callback) { - var self = this; - callback || (callback = function(){}); - - // Command to execute - var cmd = {'drop':collectionName} - - // Execute the command - this.command(cmd, {}, function(err, result) { - if(err) return callback(err, null); - if(result.ok) return callback(null, true); - callback(null, false); - }); -}; - -/** - * Rename a collection. - * - * Options - * - **dropTarget** {Boolean, default:false}, drop the target name collection if it previously exists. - * - * @param {String} fromCollection the name of the current collection we wish to rename. - * @param {String} toCollection the new name of the collection. - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from renameCollection or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {} - } - - // Add return new collection - options.new_collection = true; - - // Execute using the collection method - this.collection(fromCollection).rename(toCollection, options, callback); -}; - -/** - * Runs a command on the database. - * @ignore - * @api private - */ -Db.prototype.executeDbCommand = function(command_hash, options, callback) { - if(callback == null) { callback = options; options = {}; } - this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this, command_hash, options), options, function(err, result) { - if(callback) callback(err, result); - }); -}; - -/** - * Runs a command on the database as admin. - * @ignore - * @api private - */ -Db.prototype.executeDbAdminCommand = function(command_hash, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {} - } - - if(options.readPreference) { - options.readPreference = options.readPreference; - } - - this._executeQueryCommand(DbCommand.createAdminDbCommand(this, command_hash), options, function(err, result) { - if(callback) callback(err, result); - }); -}; - -/** - * Creates an index on the collection. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * @param {String} collectionName name of the collection to create the index on. - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from createIndex or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.createIndex = function(collectionName, fieldOrSpec, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - - // Get the error options - var writeConcern = _getWriteConcern(self, options); - // Ensure we have a callback - if(_hasWriteConcern(writeConcern) && typeof callback != 'function') { - throw new Error("Cannot use a writeConcern without a provided callback"); - } - - // Attempt to run using createIndexes command - createIndexUsingCreateIndexes(self, collectionName, fieldOrSpec, options, function(err, result) { - if(err == null) { - return callback(err, result); - } - - // Create command - var command = createCreateIndexCommand(self, collectionName, fieldOrSpec, options); - // Default command options - var commandOptions = {}; - - // If we have error conditions set handle them - if(_hasWriteConcern(writeConcern) && typeof callback == 'function') { - // Set safe option - commandOptions['safe'] = writeConcern; - // If we have an error option - if(typeof writeConcern == 'object') { - var keys = Object.keys(writeConcern); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = writeConcern[keys[i]]; - } - } - - // Execute insert command - self._executeInsertCommand(command, commandOptions, function(err, result) { - if(err != null) return callback(err, null); - if(result == null || result.documents == null) return callback(new Error("command failed to return result")); - - result = result && result.documents; - if (result[0].err) { - callback(utils.toError(result[0])); - } else { - callback(null, command.documents[0].name); - } - }); - } else { - // Execute insert command - var result = self._executeInsertCommand(command, commandOptions, function() {}); - // If no callback just return - if(!callback) return; - // If error return error - if(result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(null, null); - } - }); -}; - -var createCreateIndexCommand = function(db, collectionName, fieldOrSpec, options) { - var indexParameters = utils.parseIndexOptions(fieldOrSpec); - var fieldHash = indexParameters.fieldHash; - var keys = indexParameters.keys; - - // Generate the index name - var indexName = typeof options.name == 'string' - ? options.name - : indexParameters.name; - - var selector = { - 'ns': db.databaseName + "." + collectionName, - 'key': fieldHash, - 'name': indexName - } - - // Ensure we have a correct finalUnique - var finalUnique = options == null || 'object' === typeof options - ? false - : options; - - // Set up options - options = options == null || typeof options == 'boolean' - ? {} - : options; - - // Add all the options - var keysToOmit = Object.keys(selector); - for(var optionName in options) { - if(keysToOmit.indexOf(optionName) == -1) { - selector[optionName] = options[optionName]; - } - } - - if(selector['unique'] == null) - selector['unique'] = finalUnique; - - var name = db.databaseName + "." + DbCommand.SYSTEM_INDEX_COLLECTION; - var cmd = new InsertCommand(db, name, false); - return cmd.add(selector); -} - -var createIndexUsingCreateIndexes = function(self, collectionName, fieldOrSpec, options, callback) { - // Build the index - var indexParameters = utils.parseIndexOptions(fieldOrSpec); - // Generate the index name - var indexName = typeof options.name == 'string' - ? options.name - : indexParameters.name; - - // Set up the index - var indexes = [{ - name: indexName - , key: indexParameters.fieldHash - }]; - - // merge all the options - var keysToOmit = Object.keys(indexes[0]); - for(var optionName in options) { - if(keysToOmit.indexOf(optionName) == -1) { - indexes[0][optionName] = options[optionName]; - } - } - - // Create command - var command = {createIndexes: collectionName, indexes: indexes}; - // Build the command - self.command(command, options, function(err, result) { - if(err) return callback(err, null); - if(result.ok == 0) { - return callback(utils.toError(result), null); - } - - // Return the indexName for backward compatibility - callback(null, indexName); - }); -} - -/** - * Ensures that an index exists, if it does not it creates it - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * @param {String} collectionName name of the collection to create the index on. - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from ensureIndex or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.ensureIndex = function(collectionName, fieldOrSpec, options, callback) { - var self = this; - - if(typeof callback === 'undefined' && typeof options === 'function') { - callback = options; - options = {}; - } - - // Ensure non empty options - options = options || {}; - - // Get the error options - var writeConcern = _getWriteConcern(this, options); - // Make sure we don't try to do a write concern without a callback - if(_hasWriteConcern(writeConcern) && callback == null) - throw new Error("Cannot use a writeConcern without a provided callback"); - - // Create command - var command = createCreateIndexCommand(this, collectionName, fieldOrSpec, options); - var index_name = command.documents[0].name; - - // Check if the index allready exists - this.indexInformation(collectionName, writeConcern, function(err, indexInformation) { - if(err != null && err.code != 26) return callback(err, null); - // If the index does not exist, create it - if(indexInformation == null || !indexInformation[index_name]) { - self.createIndex(collectionName, fieldOrSpec, options, callback); - } else { - if(typeof callback === 'function') return callback(null, index_name); - } - }); -}; - -/** - * Returns the information available on allocated cursors. - * - * Options - * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from cursorInfo or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.cursorInfo = function(options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // cursorInfo command - var cmd = {'cursorInfo':1}; - - // Execute the command - this.command(cmd, options, function(err, result) { - if(err) return callback(err, null); - callback(null, result); - }); -}; - -/** - * Drop an index on a collection. - * - * @param {String} collectionName the name of the collection where the command will drop an index. - * @param {String} indexName name of the index to drop. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dropIndex or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.dropIndex = function(collectionName, indexName, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // Delete index command - var cmd = {'deleteIndexes':collectionName, 'index':indexName}; - - // Execute command - this.command(cmd, options, function(err, result) { - if(callback == null) return; - if(err) return callback(err, null); - callback(null, result); - }); -}; - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * - * @param {String} collectionName the name of the collection. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from reIndex or null if an error occurred. - * @api public -**/ -Db.prototype.reIndex = function(collectionName, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Reindex - var cmd = {'reIndex':collectionName}; - - // Execute the command - this.command(cmd, options, function(err, result) { - if(callback == null) return; - if(err) return callback(err, null); - callback(null, result.ok ? true : false); - }); -}; - -/** - * Retrieves this collections index info. - * - * Options - * - **full** {Boolean, default:false}, returns the full raw index information. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {String} collectionName the name of the collection. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from indexInformation or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.indexInformation = function(name, options, callback) { - if(typeof callback === 'undefined') { - if(typeof options === 'undefined') { - callback = name; - name = null; - } else { - callback = options; - } - options = {}; - } - - // If we specified full information - var full = options['full'] == null ? false : options['full']; - var self = this; - - // Process all the results from the index command and collection - var processResults = function(indexes) { - // Contains all the information - var info = {}; - // Process all the indexes - for(var i = 0; i < indexes.length; i++) { - var index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for(var name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - this.collection(name).listIndexes().toArray(function(err, indexes) { - if(err) return callback(utils.toError(err)); - if(full) return callback(null, indexes); - callback(null, processResults(indexes)); - }); -}; - -/** - * Drop a database. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dropDatabase or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.dropDatabase = function(options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Reindex - var cmd = {'dropDatabase':1}; - - // Execute the command - this.command(cmd, options, function(err, result) { - if(callback == null) return; - if(err) return callback(err, null); - callback(null, result.ok ? true : false); - }); -} - -/** - * Get all the db statistics. - * - * Options - * - **scale** {Number}, divide the returned sizes by scale value. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Objects} [options] options for the stats command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from stats or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.stats = function stats(options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - dbStats:true - }; - - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - - // Execute the command - this.command(commandObject, options, callback); -} - -/** - * @ignore - */ -var bindToCurrentDomain = function(callback) { - var domain = process.domain; - if(domain == null || callback == null) { - return callback; - } else { - return domain.bind(callback); - } -} - -/** - * @ignore - */ -var __executeQueryCommand = function(self, db_command, options, callback) { - // Options unpacking - var readPreference = options.readPreference != null ? options.readPreference : 'primary'; - var onAll = options['onAll'] != null ? options['onAll'] : false; - var specifiedConnection = options['connection'] != null ? options['connection'] : null; - var raw = typeof options.raw == 'boolean' ? options.raw : false; - - // Correct readPreference preference to default primary if set to false, null or primary - if(!(typeof readPreference == 'object') && readPreference._type == 'ReadPreference') { - readPreference = (readPreference == null || readPreference == 'primary' || readPreference == false) ? ReadPreference.PRIMARY : readPreference; - if(!ReadPreference.isValid(readPreference)) return callback(new Error("Illegal readPreference mode specified, " + JSON.stringify(readPreference))); - } else if(typeof readPreference == 'object' && readPreference._type == 'ReadPreference') { - if(!readPreference.isValid()) return callback(new Error("Illegal readPreference mode specified, " + JSON.stringify(readPreference))); - } - - // If we have a read preference set and we are a mongos pass the read preference on to the mongos instance, - if(self.serverConfig.isMongos() && readPreference != null && readPreference != 'primary') { - db_command.setMongosReadPreference(readPreference); - } - - // If we got a callback object - if(typeof callback === 'function' && !onAll) { - callback = bindToCurrentDomain(callback); - // Override connection if we passed in a specific connection - var connection = specifiedConnection != null ? specifiedConnection : null; - - if(connection instanceof Error) return callback(connection, null); - - // Fetch either a reader or writer dependent on the specified readPreference option if no connection - // was passed in - if(connection == null) { - connection = self.serverConfig.checkoutReader(readPreference); - } - - if(connection == null) { - return callback(new Error("no open connections")); - } else if(connection instanceof Error || connection['message'] != null) { - return callback(connection); - } - - // Exhaust Option - var exhaust = options.exhaust || false; - - // Register the handler in the data structure - self.serverConfig._registerHandler(db_command, raw, connection, exhaust, callback); - - // Write the message out and handle any errors if there are any - connection.write(db_command, function(err) { - if(err != null) { - // Call the handler with an error - if(Array.isArray(db_command)) - self.serverConfig._callHandler(db_command[0].getRequestId(), null, err); - else - self.serverConfig._callHandler(db_command.getRequestId(), null, err); - } - }); - } else if(typeof callback === 'function' && onAll) { - callback = bindToCurrentDomain(callback); - var connections = self.serverConfig.allRawConnections(); - var numberOfEntries = connections.length; - // Go through all the connections - for(var i = 0; i < connections.length; i++) { - // Fetch a connection - var connection = connections[i]; - - // Ensure we have a valid connection - if(connection == null) { - return callback(new Error("no open connections")); - } else if(connection instanceof Error) { - return callback(connection); - } - - // Register the handler in the data structure - self.serverConfig._registerHandler(db_command, raw, connection, callback); - - // Write the message out - connection.write(db_command, function(err) { - // Adjust the number of entries we need to process - numberOfEntries = numberOfEntries - 1; - // Remove listener - if(err != null) { - // Clean up listener and return error - self.serverConfig._removeHandler(db_command.getRequestId()); - } - - // No more entries to process callback with the error - if(numberOfEntries <= 0) { - callback(err); - } - }); - - // Update the db_command request id - db_command.updateRequestId(); - } - } else { - // Fetch either a reader or writer dependent on the specified read option - var connection = self.serverConfig.checkoutReader(readPreference); - // Override connection if needed - connection = specifiedConnection != null ? specifiedConnection : connection; - // Ensure we have a valid connection - if(connection == null || connection instanceof Error || connection['message'] != null) return null; - // Write the message out - connection.write(db_command, function(err) { - if(err != null) { - // Emit the error - self.emit("error", err); - } - }); - } -}; - -/** - * Execute db query command (not safe) - * @ignore - * @api private - */ -Db.prototype._executeQueryCommand = function(db_command, options, callback) { - var self = this; - - // Unpack the parameters - if(typeof options === 'function') { - callback = options; - options = {}; - } - callback = bindToCurrentDomain(callback); - - // fast fail option used for HA, no retry - var failFast = options['failFast'] != null - ? options['failFast'] - : false; - - // Check if the user force closed the command - if(this._applicationClosed) { - var err = new Error("db closed by application"); - if('function' == typeof callback) { - return callback(err, null); - } else { - throw err; - } - } - - if(this.serverConfig.isDestroyed()) - return callback(new Error("Connection was destroyed by application")); - - // Specific connection - var connection = options.connection; - // Check if the connection is actually live - if(connection - && (!connection.isConnected || !connection.isConnected())) connection = null; - - // Get the configuration - var config = this.serverConfig; - var readPreference = options.readPreference; - // Allow for the usage of the readPreference model - if(readPreference == null) { - readPreference = options.readPreference; - } - - if(!connection && !config.canRead(readPreference) && !config.canWrite() && config.isAutoReconnect()) { - - if(readPreference == ReadPreference.PRIMARY - || readPreference == ReadPreference.PRIMARY_PREFERRED - || (readPreference != null && typeof readPreference == 'object' && readPreference.mode) - || readPreference == null) { - - // Save the command - self.serverConfig._commandsStore.read_from_writer( - { type: 'query' - , db_command: db_command - , options: options - , callback: callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } else { - self.serverConfig._commandsStore.read( - { type: 'query' - , db_command: db_command - , options: options - , callback: callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } - - // If we have blown through the number of items let's - if(!self.serverConfig._commandsStore.validateBufferLimit(self.bufferMaxEntries)) { - self.close(); - } - } else if(!connection && !config.canRead(readPreference) && !config.canWrite() && !config.isAutoReconnect()) { - return callback(new Error("no open connections"), null); - } else { - if(typeof callback == 'function') { - __executeQueryCommand(self, db_command, options, function (err, result, conn) { - callback(err, result, conn); - }); - } else { - __executeQueryCommand(self, db_command, options); - } - } -}; - -/** - * @ignore - */ -var __executeInsertCommand = function(self, db_command, options, callback) { - // Always checkout a writer for this kind of operations - var connection = self.serverConfig.checkoutWriter(); - // Get safe mode - var safe = options['safe'] != null ? options['safe'] : false; - var specifiedConnection = options['connection'] != null ? options['connection'] : null; - // Override connection if needed - connection = specifiedConnection != null ? specifiedConnection : connection; - // Validate if we can use this server 2.6 wire protocol - if(connection && connection.isCompatible && !connection.isCompatible()) { - return callback(utils.toError("driver is incompatible with this server version"), null); - } - - // Ensure we have a valid connection - if(typeof callback === 'function') { - callback = bindToCurrentDomain(callback); - // Ensure we have a valid connection - if(connection == null) { - return callback(new Error("no open connections")); - } else if(connection instanceof Error) { - return callback(connection); - } - - var errorOptions = _getWriteConcern(self, options); - if(errorOptions.w > 0 || errorOptions.w == 'majority' || errorOptions.j || errorOptions.journal || errorOptions.fsync) { - // db command is now an array of commands (original command + lastError) - db_command = [db_command, DbCommand.createGetLastErrorCommand(errorOptions, self)]; - // Register the handler in the data structure - self.serverConfig._registerHandler(db_command[1], false, connection, callback); - } - } - - // If we have no callback and there is no connection - if(connection == null) return null; - if(connection instanceof Error && typeof callback == 'function') return callback(connection, null); - if(connection instanceof Error) return null; - if(connection == null && typeof callback == 'function') return callback(new Error("no primary server found"), null); - - // Write the message out - connection.write(db_command, function(err) { - // Return the callback if it's not a safe operation and the callback is defined - if(typeof callback === 'function' && (safe == null || safe == false)) { - // Perform the callback - callback(err, null); - } else if(typeof callback === 'function') { - // Call the handler with an error - self.serverConfig._callHandler(db_command[1].getRequestId(), null, err); - } else if(typeof callback == 'function' && safe && safe.w == -1) { - // Call the handler with no error - self.serverConfig._callHandler(db_command[1].getRequestId(), null, null); - } else if(!safe || safe.w == -1) { - self.emit("error", err); - } - }); -}; - -/** - * Execute an insert Command - * @ignore - * @api private - */ -Db.prototype._executeInsertCommand = function(db_command, options, callback) { - var self = this; - - // Unpack the parameters - if(callback == null && typeof options === 'function') { - callback = options; - options = {}; - } - callback = bindToCurrentDomain(callback); - // Ensure options are not null - options = options == null ? {} : options; - - // Check if the user force closed the command - if(this._applicationClosed) { - if(typeof callback == 'function') { - return callback(new Error("db closed by application"), null); - } else { - throw new Error("db closed by application"); - } - } - - if(this.serverConfig.isDestroyed()) return callback(new Error("Connection was destroyed by application")); - - // Specific connection - var connection = options.connection; - // Check if the connection is actually live - if(connection - && (!connection.isConnected || !connection.isConnected())) connection = null; - - // Get config - var config = self.serverConfig; - // Check if we are connected - if(!connection && !config.canWrite() && config.isAutoReconnect()) { - self.serverConfig._commandsStore.write( - { type:'insert' - , 'db_command':db_command - , 'options':options - , 'callback':callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - - // If we have blown through the number of items let's - if(!self.serverConfig._commandsStore.validateBufferLimit(self.bufferMaxEntries)) { - self.close(); - } - } else if(!connection && !config.canWrite() && !config.isAutoReconnect()) { - return callback(new Error("no open connections"), null); - } else { - __executeInsertCommand(self, db_command, options, callback); - } -}; - -/** - * Update command is the same - * @ignore - * @api private - */ -Db.prototype._executeUpdateCommand = Db.prototype._executeInsertCommand; -/** - * Remove command is the same - * @ignore - * @api private - */ -Db.prototype._executeRemoveCommand = Db.prototype._executeInsertCommand; - -/** - * Wrap a Mongo error document into an Error instance. - * Deprecated. Use utils.toError instead. - * - * @ignore - * @api private - * @deprecated - */ -Db.prototype.wrap = utils.toError; - -/** - * Default URL - * - * @classconstant DEFAULT_URL - **/ -Db.DEFAULT_URL = 'mongodb://localhost:27017/default'; - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Options - * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication - * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor** - * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor** - * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor** - * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor** - * - * @param {String} url connection url for MongoDB. - * @param {Object} [options] optional options for insert command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the db instance or null if an error occurred. - * @return {null} - * @api public - */ -Db.connect = function(url, options, callback) { - // Ensure correct mapping of the callback - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Ensure same behavior as previous version w:0 - if(url.indexOf("safe") == -1 - && url.indexOf("w") == -1 - && url.indexOf("journal") == -1 && url.indexOf("j") == -1 - && url.indexOf("fsync") == -1) options.w = 1; - - // Avoid circular require problem - var MongoClient = require('./mongo_client.js').MongoClient; - // Attempt to connect - MongoClient.connect.call(MongoClient, url, options, callback); -}; - -/** - * State of the db connection - * @ignore - */ -Object.defineProperty(Db.prototype, "state", { enumerable: true - , get: function () { - return this.serverConfig._serverState; - } -}); - -/** - * @ignore - */ -var _hasWriteConcern = function(errorOptions) { - return errorOptions == true - || errorOptions.w > 0 - || errorOptions.w == 'majority' - || errorOptions.j == true - || errorOptions.journal == true - || errorOptions.fsync == true -}; - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -}; - -/** - * @ignore - */ -var _getWriteConcern = function(self, options) { - // Final options - var finalOptions = {w:1}; - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.options); - } else if(self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.safe); - } else if(typeof self.safe == "boolean") { - finalOptions = {w: (self.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true"); - - // Return the options - return finalOptions; -} - -/** - * Legacy support - * - * @ignore - * @api private - */ -exports.connect = Db.connect; -exports.Db = Db; - -/** - * Remove all listeners to the db instance. - * @ignore - * @api private - */ -Db.prototype.removeAllEventListeners = function() { - this.removeAllListeners("close"); - this.removeAllListeners("error"); - this.removeAllListeners("timeout"); - this.removeAllListeners("parseError"); - this.removeAllListeners("poolReady"); - this.removeAllListeners("message"); -}; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/gridfs/chunk.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/gridfs/chunk.js deleted file mode 100755 index 8cddafe6..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/gridfs/chunk.js +++ /dev/null @@ -1,232 +0,0 @@ -var Binary = require('bson').Binary, - ObjectID = require('bson').ObjectID; - -/** - * Class for representing a single chunk in GridFS. - * - * @class - * - * @param file {GridStore} The {@link GridStore} object holding this chunk. - * @param mongoObject {object} The mongo object representation of this chunk. - * - * @throws Error when the type of data field for {@link mongoObject} is not - * supported. Currently supported types for data field are instances of - * {@link String}, {@link Array}, {@link Binary} and {@link Binary} - * from the bson module - * - * @see Chunk#buildMongoObject - */ -var Chunk = exports.Chunk = function(file, mongoObject, writeConcern) { - if(!(this instanceof Chunk)) return new Chunk(file, mongoObject); - - this.file = file; - var self = this; - var mongoObjectFinal = mongoObject == null ? {} : mongoObject; - this.writeConcern = writeConcern || {w:1}; - this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; - this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; - this.data = new Binary(); - - if(mongoObjectFinal.data == null) { - } else if(typeof mongoObjectFinal.data == "string") { - var buffer = new Buffer(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 'binary', 0); - this.data = new Binary(buffer); - } else if(Array.isArray(mongoObjectFinal.data)) { - var buffer = new Buffer(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data.join(''), 'binary', 0); - this.data = new Binary(buffer); - } else if(mongoObjectFinal.data instanceof Binary || mongoObjectFinal.data._bsontype === 'Binary' || Object.prototype.toString.call(mongoObjectFinal.data) == "[object Binary]") { - this.data = mongoObjectFinal.data; - } else if(Buffer.isBuffer(mongoObjectFinal.data)) { - } else { - throw Error("Illegal chunk format"); - } - - // Update position - this.internalPosition = 0; -}; - -/** - * Writes a data to this object and advance the read/write head. - * - * @param data {string} the data to write - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.write = function(data, callback) { - this.data.write(data, this.internalPosition); - this.internalPosition = this.data.length(); - if(callback != null) return callback(null, this); - return this; -}; - -/** - * Reads data and advances the read/write head. - * - * @param length {number} The length of data to read. - * - * @return {string} The data read if the given length will not exceed the end of - * the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.read = function(length) { - // Default to full read if no index defined - length = length == null || length == 0 ? this.length() : length; - - if(this.length() - this.internalPosition + 1 >= length) { - var data = this.data.read(this.internalPosition, length); - this.internalPosition = this.internalPosition + length; - return data; - } else { - return ''; - } -}; - -Chunk.prototype.readSlice = function(length) { - if ((this.length() - this.internalPosition) >= length) { - var data = null; - if (this.data.buffer != null) { //Pure BSON - data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); - } else { //Native BSON - data = new Buffer(length); - length = this.data.readInto(data, this.internalPosition); - } - this.internalPosition = this.internalPosition + length; - return data; - } else { - return null; - } -}; - -/** - * Checks if the read/write head is at the end. - * - * @return {boolean} Whether the read/write head has reached the end of this - * chunk. - */ -Chunk.prototype.eof = function() { - return this.internalPosition == this.length() ? true : false; -}; - -/** - * Reads one character from the data of this chunk and advances the read/write - * head. - * - * @return {string} a single character data read if the the read/write head is - * not at the end of the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.getc = function() { - return this.read(1); -}; - -/** - * Clears the contents of the data in this chunk and resets the read/write head - * to the initial position. - */ -Chunk.prototype.rewind = function() { - this.internalPosition = 0; - this.data = new Binary(); -}; - -/** - * Saves this chunk to the database. Also overwrites existing entries having the - * same id as this chunk. - * - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.save = function(options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {}; - } - - self.file.chunkCollection(function(err, collection) { - if(err) return callback(err); - - // Merge the options - var writeOptions = {}; - for(var name in options) writeOptions[name] = options[name]; - for(var name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; - - // collection.remove({'_id':self.objectId}, self.writeConcern, function(err, result) { - collection.remove({'_id':self.objectId}, writeOptions, function(err, result) { - if(err) return callback(err); - - if(self.data.length() > 0) { - self.buildMongoObject(function(mongoObject) { - var options = {forceServerObjectId:true}; - for(var name in self.writeConcern) { - options[name] = self.writeConcern[name]; - } - - collection.insert(mongoObject, writeOptions, function(err, collection) { - callback(err, self); - }); - }); - } else { - callback(null, self); - } - }); - }); -}; - -/** - * Creates a mongoDB object representation of this chunk. - * - * @param callback {function(Object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *

- *        {
- *          '_id' : , // {number} id for this chunk
- *          'files_id' : , // {number} foreign key to the file collection
- *          'n' : , // {number} chunk number
- *          'data' : , // {bson#Binary} the chunk data itself
- *        }
- *        
- * - * @see MongoDB GridFS Chunk Object Structure - */ -Chunk.prototype.buildMongoObject = function(callback) { - var mongoObject = { - 'files_id': this.file.fileId, - 'n': this.chunkNumber, - 'data': this.data}; - // If we are saving using a specific ObjectId - if(this.objectId != null) mongoObject._id = this.objectId; - - callback(mongoObject); -}; - -/** - * @return {number} the length of the data - */ -Chunk.prototype.length = function() { - return this.data.length(); -}; - -/** - * The position of the read/write head - * @name position - * @lends Chunk# - * @field - */ -Object.defineProperty(Chunk.prototype, "position", { enumerable: true - , get: function () { - return this.internalPosition; - } - , set: function(value) { - this.internalPosition = value; - } -}); - -/** - * The default chunk size - * @constant - */ -Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/gridfs/grid.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/gridfs/grid.js deleted file mode 100755 index 00db0efd..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/gridfs/grid.js +++ /dev/null @@ -1,104 +0,0 @@ -var GridStore = require('./gridstore').GridStore, - ObjectID = require('bson').ObjectID; - -/** - * A class representation of a simple Grid interface. - * - * @class Represents the Grid. - * @param {Db} db A database instance to interact with. - * @param {String} [fsName] optional different root collection for GridFS. - * @return {Grid} - */ -function Grid(db, fsName) { - - if(!(this instanceof Grid)) return new Grid(db, fsName); - - this.db = db; - this.fsName = fsName == null ? GridStore.DEFAULT_ROOT_COLLECTION : fsName; -} - -/** - * Puts binary data to the grid - * - * Options - * - **_id** {Any}, unique id for this file - * - **filename** {String}, name for this file. - * - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * - **metadata** {Object}, arbitrary data the user wants to store. - * - * @param {Buffer} data buffer with Binary Data. - * @param {Object} [options] the options for the files. - * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -Grid.prototype.put = function(data, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - // If root is not defined add our default one - options['root'] = options['root'] == null ? this.fsName : options['root']; - - // Return if we don't have a buffer object as data - if(!(Buffer.isBuffer(data))) return callback(new Error("Data object must be a buffer object"), null); - // Get filename if we are using it - var filename = options['filename'] || null; - // Get id if we are using it - var id = options['_id'] || null; - // Create gridstore - var gridStore = new GridStore(this.db, id, filename, "w", options); - gridStore.open(function(err, gridStore) { - if(err) return callback(err, null); - - gridStore.write(data, function(err, result) { - if(err) return callback(err, null); - - gridStore.close(function(err, result) { - if(err) return callback(err, null); - callback(null, result); - }) - }) - }) -} - -/** - * Get binary data to the grid - * - * @param {Any} id for file. - * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -Grid.prototype.get = function(id, callback) { - // Create gridstore - var gridStore = new GridStore(this.db, id, null, "r", {root:this.fsName}); - gridStore.open(function(err, gridStore) { - if(err) return callback(err, null); - - // Return the data - gridStore.read(function(err, data) { - return callback(err, data) - }); - }) -} - -/** - * Delete file from grid - * - * @param {Any} id for file. - * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -Grid.prototype.delete = function(id, callback) { - // Create gridstore - GridStore.unlink(this.db, id, {root:this.fsName}, function(err, result) { - if(err) return callback(err, false); - return callback(null, true); - }); -} - -exports.Grid = Grid; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js deleted file mode 100755 index c6b98946..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js +++ /dev/null @@ -1,1570 +0,0 @@ -/** - * @fileOverview GridFS is a tool for MongoDB to store files to the database. - * Because of the restrictions of the object size the database can hold, a - * facility to split a file into several chunks is needed. The {@link GridStore} - * class offers a simplified api to interact with files while managing the - * chunks of split files behind the scenes. More information about GridFS can be - * found here. - */ -var Chunk = require('./chunk').Chunk, - DbCommand = require('../commands/db_command').DbCommand, - ObjectID = require('bson').ObjectID, - Buffer = require('buffer').Buffer, - fs = require('fs'), - timers = require('timers'), - util = require('util'), - inherits = util.inherits, - ReadStream = require('./readstream').ReadStream, - Stream = require('stream'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -var REFERENCE_BY_FILENAME = 0, - REFERENCE_BY_ID = 1; - -/** - * A class representation of a file stored in GridFS. - * - * Modes - * - **"r"** - read only. This is the default mode. - * - **"w"** - write in truncate mode. Existing data will be overwriten. - * - **w+"** - write in edit mode (append is not guaranteed for concurrent operations) - * - * Options - * - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * - **metadata** {Object}, arbitrary data the user wants to store. - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - * @class Represents the GridStore. - * @param {Db} db A database instance to interact with. - * @param {Any} [id] optional unique id for this file - * @param {String} [filename] optional filename for this file, no unique constrain on the field - * @param {String} mode set the mode for this file. - * @param {Object} options optional properties to specify. - * @return {GridStore} - */ -var GridStore = function GridStore(db, id, filename, mode, options) { - if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); - - var self = this; - this.db = db; - - // Call stream constructor - if(typeof Stream == 'function') { - Stream.call(this); - } - - // Handle options - if(typeof options === 'undefined') options = {}; - // Handle mode - if(typeof mode === 'undefined') { - mode = filename; - filename = undefined; - } else if(typeof mode == 'object') { - options = mode; - mode = filename; - filename = undefined; - } - - if(id instanceof ObjectID) { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } else if(typeof filename == 'undefined') { - this.referenceBy = REFERENCE_BY_FILENAME; - this.filename = id; - if (mode.indexOf('w') != null) { - this.fileId = new ObjectID(); - } - } else { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } - - // Set up the rest - this.mode = mode == null ? "r" : mode; - this.options = options || {}; - - // Set the root if overridden - this.root = this.options['root'] == null ? exports.GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; - this.position = 0; - this.readPreference = this.options.readPreference || 'primary'; - this.writeConcern = _getWriteConcern(db, this.options); - - // Set default chunk size - this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; -} - -/** - * Code for the streaming capabilities of the gridstore object - * Most code from Aaron heckmanns project https://github.com/aheckmann/gridfs-stream - * Modified to work on the gridstore object itself - * @ignore - */ -if(typeof Stream == 'function') { - GridStore.prototype = { __proto__: Stream.prototype } -} else { - // Node 0.4.X compatibility code - GridStore.prototype = { __proto__: Stream.Stream.prototype } -} - -// Move pipe to _pipe -GridStore.prototype._pipe = GridStore.prototype.pipe; - -/** - * Opens the file from the database and initialize this object. Also creates a - * new one if file does not exist. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain an **{Error}** object and the second parameter will be null if an error occured. Otherwise, the first parameter will be null and the second will contain the reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.open = function(callback) { - if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ - callback(new Error("Illegal mode " + this.mode), null); - return; - } - - var self = this; - - // Get the write concern - var writeConcern = _getWriteConcern(this.db, this.options); - - // If we are writing we need to ensure we have the right indexes for md5's - if((self.mode == "w" || self.mode == "w+")) { - // Get files collection - var collection = self.collection(); - // Put index on filename - collection.ensureIndex([['filename', 1]], writeConcern, function(err, index) { - // if(err) return callback(err); - - // Get chunk collection - var chunkCollection = self.chunkCollection(); - // Ensure index on chunk collection - chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], writeConcern, function(err, index) { - // if(err) return callback(err); - _open(self, writeConcern, callback); - }); - }); - } else { - // Open the gridstore - _open(self, writeConcern, callback); - } -}; - -/** - * Hidding the _open function - * @ignore - * @api private - */ -var _open = function(self, options, callback) { - var collection = self.collection(); - // Create the query - var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename}; - query = null == self.fileId && self.filename == null ? null : query; - options.readPreference = self.readPreference; - - // Fetch the chunks - if(query != null) { - collection.findOne(query, options, function(err, doc) { - if(err) return error(err); - - // Check if the collection for the files exists otherwise prepare the new one - if(doc != null) { - self.fileId = doc._id; - // Prefer a new filename over the existing one if this is a write - self.filename = ((self.mode == 'r') || (self.filename == undefined)) ? doc.filename : self.filename; - self.contentType = doc.contentType; - self.internalChunkSize = doc.chunkSize; - self.uploadDate = doc.uploadDate; - self.aliases = doc.aliases; - self.length = doc.length; - self.metadata = doc.metadata; - self.internalMd5 = doc.md5; - } else if (self.mode != 'r') { - self.fileId = self.fileId == null ? new ObjectID() : self.fileId; - self.contentType = exports.GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - } else { - self.length = 0; - var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId; - return error(new Error((self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename) + " does not exist", self)); - } - - // Process the mode of the object - if(self.mode == "r") { - nthChunk(self, 0, options, function(err, chunk) { - if(err) return error(err); - self.currentChunk = chunk; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, options, function(err, result) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - }); - } else { - // Write only mode - self.fileId = null == self.fileId ? new ObjectID() : self.fileId; - self.contentType = exports.GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - - var collection2 = self.chunkCollection(); - // No file exists set up write mode - if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, options, function(err, result) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - } - - // only pass error to callback once - function error (err) { - if(error.err) return; - callback(error.err = err); - } -}; - -/** - * Stores a file from the file system to the GridFS database. - * - * @param {String|Buffer|FileHandle} file the file to store. - * @param {Function} callback this will be called after this method is executed. The first parameter will be null and the the second will contain the reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.writeFile = function (file, callback) { - var self = this; - if (typeof file === 'string') { - fs.open(file, 'r', function (err, fd) { - if(err) return callback(err); - self.writeFile(fd, callback); - }); - return; - } - - self.open(function (err, self) { - if(err) return callback(err, self); - - fs.fstat(file, function (err, stats) { - if(err) return callback(err, self); - - var offset = 0; - var index = 0; - var numberOfChunksLeft = Math.min(stats.size / self.chunkSize); - - // Write a chunk - var writeChunk = function() { - fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) { - if(err) return callback(err, self); - - offset = offset + bytesRead; - - // Create a new chunk for the data - var chunk = new Chunk(self, {n:index++}, self.writeConcern); - chunk.write(data, function(err, chunk) { - if(err) return callback(err, self); - - chunk.save({}, function(err, result) { - if(err) return callback(err, self); - - self.position = self.position + data.length; - - // Point to current chunk - self.currentChunk = chunk; - - if(offset >= stats.size) { - fs.close(file); - self.close(function(err, result) { - if(err) return callback(err, self); - return callback(null, self); - }); - } else { - return processor(writeChunk); - } - }); - }); - }); - } - - // Process the first write - processor(writeChunk); - }); - }); -}; - -/** - * Writes some data. This method will work properly only if initialized with mode - * "w" or "w+". - * - * @param string {string} The data to write. - * @param close {boolean=false} opt_argument Closes this file after writing if - * true. - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - * - * @ignore - * @api private - */ -var writeBuffer = function(self, buffer, close, callback) { - if(typeof close === "function") { callback = close; close = null; } - var finalClose = typeof close == 'boolean' ? close : false; - - if(self.mode[0] != "w") { - callback(new Error((self.referenceBy == REFERENCE_BY_ID ? self.toHexString() : self.filename) + " not opened for writing"), null); - } else { - if(self.currentChunk.position + buffer.length >= self.chunkSize) { - // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left - // to a new chunk (recursively) - var previousChunkNumber = self.currentChunk.chunkNumber; - var leftOverDataSize = self.chunkSize - self.currentChunk.position; - var firstChunkData = buffer.slice(0, leftOverDataSize); - var leftOverData = buffer.slice(leftOverDataSize); - // A list of chunks to write out - var chunksToWrite = [self.currentChunk.write(firstChunkData)]; - // If we have more data left than the chunk size let's keep writing new chunks - while(leftOverData.length >= self.chunkSize) { - // Create a new chunk and write to it - var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - var firstChunkData = leftOverData.slice(0, self.chunkSize); - leftOverData = leftOverData.slice(self.chunkSize); - // Update chunk number - previousChunkNumber = previousChunkNumber + 1; - // Write data - newChunk.write(firstChunkData); - // Push chunk to save list - chunksToWrite.push(newChunk); - } - - // Set current chunk with remaining data - self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - // If we have left over data write it - if(leftOverData.length > 0) self.currentChunk.write(leftOverData); - - // Update the position for the gridstore - self.position = self.position + buffer.length; - // Total number of chunks to write - var numberOfChunksToWrite = chunksToWrite.length; - - for(var i = 0; i < chunksToWrite.length; i++) { - chunksToWrite[i].save({}, function(err, result) { - if(err) return callback(err); - - numberOfChunksToWrite = numberOfChunksToWrite - 1; - - if(numberOfChunksToWrite <= 0) { - // We care closing the file before returning - if(finalClose) { - return self.close(function(err, result) { - callback(err, self); - }); - } - - // Return normally - return callback(null, self); - } - }); - } - } else { - // Update the position for the gridstore - self.position = self.position + buffer.length; - // We have less data than the chunk size just write it and callback - self.currentChunk.write(buffer); - // We care closing the file before returning - if(finalClose) { - return self.close(function(err, result) { - callback(err, self); - }); - } - // Return normally - return callback(null, self); - } - } -}; - -/** - * Creates a mongoDB object representation of this object. - * - * @param callback {function(object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *

- *        {
- *          '_id' : , // {number} id for this file
- *          'filename' : , // {string} name for this file
- *          'contentType' : , // {string} mime type for this file
- *          'length' : , // {number} size of this file?
- *          'chunksize' : , // {number} chunk size used by this file
- *          'uploadDate' : , // {Date}
- *          'aliases' : , // {array of string}
- *          'metadata' : , // {string}
- *        }
- *        
- * - * @ignore - * @api private - */ -var buildMongoObject = function(self, callback) { - // Calcuate the length - var mongoObject = { - '_id': self.fileId, - 'filename': self.filename, - 'contentType': self.contentType, - 'length': self.position ? self.position : 0, - 'chunkSize': self.chunkSize, - 'uploadDate': self.uploadDate, - 'aliases': self.aliases, - 'metadata': self.metadata - }; - - var md5Command = {filemd5:self.fileId, root:self.root}; - self.db.command(md5Command, function(err, results) { - if(err) return callback(err); - - mongoObject.md5 = results.md5; - callback(null, mongoObject); - }); -}; - -/** - * Saves this file to the database. This will overwrite the old entry if it - * already exists. This will work properly only if mode was initialized to - * "w" or "w+". - * - * @param {Function} callback this will be called after executing this method. Passes an **{Error}** object to the first parameter and null to the second if an error occured. Otherwise, passes null to the first and a reference to this object to the second. - * @return {null} - * @api public - */ -GridStore.prototype.close = function(callback) { - var self = this; - - if(self.mode[0] == "w") { - // Set up options - var options = self.writeConcern; - - if(self.currentChunk != null && self.currentChunk.position > 0) { - self.currentChunk.save({}, function(err, chunk) { - if(err && typeof callback == 'function') return callback(err); - - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - // Build the mongo object - if(self.uploadDate != null) { - files.remove({'_id':self.fileId}, self.writeConcern, function(err, collection) { - if(err && typeof callback == 'function') return callback(err); - - buildMongoObject(self, function(err, mongoObject) { - if(err) { - if(typeof callback == 'function') return callback(err); else throw err; - } - - files.save(mongoObject, options, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } else { - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if(err) { - if(typeof callback == 'function') return callback(err); else throw err; - } - - files.save(mongoObject, options, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - } - }); - }); - } else { - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if(err) { - if(typeof callback == 'function') return callback(err); else throw err; - } - - files.save(mongoObject, options, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } - } else if(self.mode[0] == "r") { - if(typeof callback == 'function') - callback(null, null); - } else { - if(typeof callback == 'function') - callback(new Error("Illegal mode " + self.mode), null); - } -}; - -/** - * Gets the nth chunk of this file. - * - * @param chunkNumber {number} The nth chunk to retrieve. - * @param callback {function(*, Chunk|object)} This will be called after - * executing this method. null will be passed to the first parameter while - * a new {@link Chunk} instance will be passed to the second parameter if - * the chunk was found or an empty object {} if not. - * - * @ignore - * @api private - */ -var nthChunk = function(self, chunkNumber, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - options.readPreference = self.readPreference; - // Get the nth chunk - self.chunkCollection().findOne({'files_id':self.fileId, 'n':chunkNumber}, options, function(err, chunk) { - if(err) return callback(err); - - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - }); -}; - -/** - * - * @ignore - * @api private - */ -GridStore.prototype._nthChunk = function(chunkNumber, callback) { - nthChunk(this, chunkNumber, callback); -} - -/** - * @return {Number} The last chunk number of this file. - * - * @ignore - * @api private - */ -var lastChunkNumber = function(self) { - return Math.floor((self.length ? self.length - 1 : 0)/self.chunkSize); -}; - -/** - * Retrieve this file's chunks collection. - * - * @param {Function} callback this will be called after executing this method. An exception object will be passed to the first parameter when an error occured or null otherwise. A new **{Collection}** object will be passed to the second parameter if no error occured. - * @return {null} - * @api public - */ -GridStore.prototype.chunkCollection = function(callback) { - if(typeof callback == 'function') - return this.db.collection((this.root + ".chunks"), callback); - return this.db.collection((this.root + ".chunks")); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @param callback {function(*, boolean)} This will be called after this method - * executes. Passes null to the first and true to the second argument. - * - * @ignore - * @api private - */ -var deleteChunks = function(self, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - - if(self.fileId != null) { - self.chunkCollection().remove({'files_id':self.fileId}, options, function(err, result) { - if(err) return callback(err, false); - callback(null, true); - }); - } else { - callback(null, true); - } -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @param {Function} callback this will be called after this method executes. Passes null to the first and true to the second argument. - * @return {null} - * @api public - */ -GridStore.prototype.unlink = function(callback) { - var self = this; - deleteChunks(this, function(err) { - if(err!==null) { - err.message = "at deleteChunks: " + err.message; - return callback(err); - } - - self.collection(function(err, collection) { - if(err!==null) { - err.message = "at collection: " + err.message; - return callback(err); - } - - collection.remove({'_id':self.fileId}, self.writeConcern, function(err) { - callback(err, self); - }); - }); - }); -}; - -/** - * Retrieves the file collection associated with this object. - * - * @param {Function} callback this will be called after executing this method. An exception object will be passed to the first parameter when an error occured or null otherwise. A new **{Collection}** object will be passed to the second parameter if no error occured. - * @return {null} - * @api public - */ -GridStore.prototype.collection = function(callback) { - if(typeof callback == 'function') - this.db.collection(this.root + ".files", callback); - return this.db.collection(this.root + ".files"); -}; - -/** - * Reads the data of this file. - * - * @param {String} [separator] the character to be recognized as the newline separator. - * @param {Function} callback This will be called after this method is executed. The first parameter will be null and the second parameter will contain an array of strings representing the entire data, each element representing a line including the separator character. - * @return {null} - * @api public - */ -GridStore.prototype.readlines = function(separator, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - separator = args.length ? args.shift() : "\n"; - - this.read(function(err, data) { - if(err) return callback(err); - - var items = data.toString().split(separator); - items = items.length > 0 ? items.splice(0, items.length - 1) : []; - for(var i = 0; i < items.length; i++) { - items[i] = items[i] + separator; - } - - callback(null, items); - }); -}; - -/** - * Deletes all the chunks of this file in the database if mode was set to "w" or - * "w+" and resets the read/write head to the initial position. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.rewind = function(callback) { - var self = this; - - if(this.currentChunk.chunkNumber != 0) { - if(this.mode[0] == "w") { - deleteChunks(self, function(err, gridStore) { - if(err) return callback(err); - self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern); - self.position = 0; - callback(null, self); - }); - } else { - self.currentChunk(0, function(err, chunk) { - if(err) return callback(err); - self.currentChunk = chunk; - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - }); - } - } else { - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - } -}; - -/** - * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. - * - * There are 3 signatures for this method: - * - * (callback) - * (length, callback) - * (length, buffer, callback) - * - * @param {Number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {String|Buffer} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {Function} callback this will be called after this method is executed. null will be passed to the first parameter and a string containing the contents of the buffer concatenated with the contents read from this file will be passed to the second. - * @return {null} - * @api public - */ -GridStore.prototype.read = function(length, buffer, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - length = args.length ? args.shift() : null; - buffer = args.length ? args.shift() : null; - - // The data is a c-terminated string and thus the length - 1 - var finalLength = length == null ? self.length - self.position : length; - var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer; - // Add a index to buffer to keep track of writing position or apply current index - finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; - - if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) { - var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update internal position - self.position = self.position + finalBuffer.length; - // Check if we don't have a file at all - if(finalLength == 0 && finalBuffer.length == 0) return callback(new Error("File does not exist"), null); - // Else return data - callback(null, finalBuffer); - } else { - var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update index position - finalBuffer._index += slice.length; - - // Load next chunk and read more - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - if(err) return callback(err); - - if(chunk.length() > 0) { - self.currentChunk = chunk; - self.read(length, finalBuffer, callback); - } else { - if (finalBuffer._index > 0) { - callback(null, finalBuffer) - } else { - callback(new Error("no chunks found for file, possibly corrupt"), null); - } - } - }); - } -} - -/** - * Retrieves the position of the read/write head of this file. - * - * @param {Function} callback This gets called after this method terminates. null is passed to the first parameter and the position is passed to the second. - * @return {null} - * @api public - */ -GridStore.prototype.tell = function(callback) { - callback(null, this.position); -}; - -/** - * Moves the read/write head to a new location. - * - * There are 3 signatures for this method - * - * Seek Location Modes - * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. - * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. - * - **GridStore.IO_SEEK_END**, set the position from the end of the file. - * - * @param {Number} [position] the position to seek to - * @param {Number} [seekLocation] seek mode. Use one of the Seek Location modes. - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.seek = function(position, seekLocation, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - seekLocation = args.length ? args.shift() : null; - - var seekLocationFinal = seekLocation == null ? exports.GridStore.IO_SEEK_SET : seekLocation; - var finalPosition = position; - var targetPosition = 0; - - // Calculate the position - if(seekLocationFinal == exports.GridStore.IO_SEEK_CUR) { - targetPosition = self.position + finalPosition; - } else if(seekLocationFinal == exports.GridStore.IO_SEEK_END) { - targetPosition = self.length + finalPosition; - } else { - targetPosition = finalPosition; - } - - // Get the chunk - var newChunkNumber = Math.floor(targetPosition/self.chunkSize); - if(newChunkNumber != self.currentChunk.chunkNumber) { - var seekChunk = function() { - nthChunk(self, newChunkNumber, function(err, chunk) { - self.currentChunk = chunk; - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(err, self); - }); - }; - - if(self.mode[0] == 'w') { - self.currentChunk.save({}, function(err) { - if(err) return callback(err); - seekChunk(); - }); - } else { - seekChunk(); - } - } else { - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(null, self); - } -}; - -/** - * Verify if the file is at EOF. - * - * @return {Boolean} true if the read/write head is at the end of this file. - * @api public - */ -GridStore.prototype.eof = function() { - return this.position == this.length ? true : false; -}; - -/** - * Retrieves a single character from this file. - * - * @param {Function} callback this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. - * @return {null} - * @api public - */ -GridStore.prototype.getc = function(callback) { - var self = this; - - if(self.eof()) { - callback(null, null); - } else if(self.currentChunk.eof()) { - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - self.currentChunk = chunk; - self.position = self.position + 1; - callback(err, self.currentChunk.getc()); - }); - } else { - self.position = self.position + 1; - callback(null, self.currentChunk.getc()); - } -}; - -/** - * Writes a string to the file with a newline character appended at the end if - * the given string does not have one. - * - * @param {String} string the string to write. - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.puts = function(string, callback) { - var finalString = string.match(/\n$/) == null ? string + "\n" : string; - this.write(finalString, callback); -}; - -/** - * Returns read stream based on this GridStore file - * - * Events - * - **data** {function(item) {}} the data event triggers when a document is ready. - * - **end** {function() {}} the end event triggers when there is no more documents available. - * - **close** {function() {}} the close event triggers when the stream is closed. - * - **error** {function(err) {}} the error event triggers if an error happens. - * - * @param {Boolean} autoclose if true current GridStore will be closed when EOF and 'close' event will be fired - * @return {null} - * @api public - */ -GridStore.prototype.stream = function(autoclose) { - return new ReadStream(autoclose, this); -}; - -/** -* The collection to be used for holding the files and chunks collection. -* -* @classconstant DEFAULT_ROOT_COLLECTION -**/ -GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; - -/** -* Default file mime type -* -* @classconstant DEFAULT_CONTENT_TYPE -**/ -GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; - -/** -* Seek mode where the given length is absolute. -* -* @classconstant IO_SEEK_SET -**/ -GridStore.IO_SEEK_SET = 0; - -/** -* Seek mode where the given length is an offset to the current read/write head. -* -* @classconstant IO_SEEK_CUR -**/ -GridStore.IO_SEEK_CUR = 1; - -/** -* Seek mode where the given length is an offset to the end of the file. -* -* @classconstant IO_SEEK_END -**/ -GridStore.IO_SEEK_END = 2; - -/** - * Checks if a file exists in the database. - * - * Options - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Db} db the database to query. - * @param {String} name the name of the file to look for. - * @param {String} [rootCollection] the root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {Function} callback this will be called after this method executes. Passes null to the first and passes true to the second if the file exists and false otherwise. - * @return {null} - * @api public - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - // Establish read preference - var readPreference = options.readPreference || 'primary'; - // Fetch collection - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - db.collection(rootCollectionFinal + ".files", function(err, collection) { - if(err) return callback(err); - - // Build query - var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' ) - ? {'filename':fileIdObject} - : {'_id':fileIdObject}; // Attempt to locate file - - collection.findOne(query, {readPreference:readPreference}, function(err, item) { - if(err) return callback(err); - - callback(null, item == null ? false : true); - }); - }); -}; - -/** - * Gets the list of files stored in the GridFS. - * - * @param {Db} db the database to query. - * @param {String} [rootCollection] the root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {Function} callback this will be called after this method executes. Passes null to the first and passes an array of strings containing the names of the files. - * @return {null} - * @api public - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - // Ensure we have correct values - if(rootCollection != null && typeof rootCollection == 'object') { - options = rootCollection; - rootCollection = null; - } - - // Establish read preference - var readPreference = options.readPreference || 'primary'; - // Check if we are returning by id not filename - var byId = options['id'] != null ? options['id'] : false; - // Fetch item - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - var items = []; - db.collection((rootCollectionFinal + ".files"), function(err, collection) { - if(err) return callback(err); - - collection.find({}, {readPreference:readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.each(function(err, item) { - if(item != null) { - items.push(byId ? item._id : item.filename); - } else { - callback(err, items); - } - }); - }); - }); -}; - -/** - * Reads the contents of a file. - * - * This method has the following signatures - * - * (db, name, callback) - * (db, name, length, callback) - * (db, name, length, offset, callback) - * (db, name, length, offset, options, callback) - * - * @param {Db} db the database to query. - * @param {String} name the name of the file. - * @param {Number} [length] the size of data to read. - * @param {Number} [offset] the offset from the head of the file of which to start reading from. - * @param {Object} [options] the options for the file. - * @param {Function} callback this will be called after this method executes. A string with an error message will be passed to the first parameter when the length and offset combination exceeds the length of the file while an Error object will be passed if other forms of error occured, otherwise, a string is passed. The second parameter will contain the data read if successful or null if an error occured. - * @return {null} - * @api public - */ -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - // Make sure we are not reading out of bounds - if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null); - if(length && length > gridStore.length) return callback("length is larger than the size of the file", null); - if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null); - - if(offset != null) { - gridStore.seek(offset, function(err, gridStore) { - if(err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); -}; - -/** - * Reads the data of this file. - * - * @param {Db} db the database to query. - * @param {String} name the name of the file. - * @param {String} [separator] the character to be recognized as the newline separator. - * @param {Object} [options] file options. - * @param {Function} callback this will be called after this method is executed. The first parameter will be null and the second parameter will contain an array of strings representing the entire data, each element representing a line including the separator character. - * @return {null} - * @api public - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - - var finalSeperator = separator == null ? "\n" : separator; - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - gridStore.readlines(finalSeperator, callback); - }); -}; - -/** - * Deletes the chunks and metadata information of a file from GridFS. - * - * @param {Db} db the database to interact with. - * @param {String|Array} names the name/names of the files to delete. - * @param {Object} [options] the options for the files. - * @callback {Function} this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.unlink = function(db, names, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() : {}; - - // Get the write concern - var writeConcern = _getWriteConcern(db, options); - - // List of names - if(names.constructor == Array) { - var tc = 0; - for(var i = 0; i < names.length; i++) { - ++tc; - GridStore.unlink(db, names[i], options, function(result) { - if(--tc == 0) { - callback(null, self); - } - }); - } - } else { - new GridStore(db, names, "w", options).open(function(err, gridStore) { - if(err) return callback(err); - deleteChunks(gridStore, function(err, result) { - if(err) return callback(err); - gridStore.collection(function(err, collection) { - if(err) return callback(err); - collection.remove({'_id':gridStore.fileId}, writeConcern, function(err, result) { - callback(err, self); - }); - }); - }); - }); - } -}; - -/** - * Returns the current chunksize of the file. - * - * @field chunkSize - * @type {Number} - * @getter - * @setter - * @property return number of bytes in the current chunkSize. - */ -Object.defineProperty(GridStore.prototype, "chunkSize", { enumerable: true - , get: function () { - return this.internalChunkSize; - } - , set: function(value) { - if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) { - this.internalChunkSize = this.internalChunkSize; - } else { - this.internalChunkSize = value; - } - } -}); - -/** - * The md5 checksum for this file. - * - * @field md5 - * @type {Number} - * @getter - * @setter - * @property return this files md5 checksum. - */ -Object.defineProperty(GridStore.prototype, "md5", { enumerable: true - , get: function () { - return this.internalMd5; - } -}); - -/** - * GridStore Streaming methods - * Handles the correct return of the writeable stream status - * @ignore - */ -Object.defineProperty(GridStore.prototype, "writable", { enumerable: true - , get: function () { - if(this._writeable == null) { - this._writeable = this.mode != null && this.mode.indexOf("w") != -1; - } - // Return the _writeable - return this._writeable; - } - , set: function(value) { - this._writeable = value; - } -}); - -/** - * Handles the correct return of the readable stream status - * @ignore - */ -Object.defineProperty(GridStore.prototype, "readable", { enumerable: true - , get: function () { - if(this._readable == null) { - this._readable = this.mode != null && this.mode.indexOf("r") != -1; - } - return this._readable; - } - , set: function(value) { - this._readable = value; - } -}); - -GridStore.prototype.paused; - -/** - * Handles the correct setting of encoding for the stream - * @ignore - */ -GridStore.prototype.setEncoding = fs.ReadStream.prototype.setEncoding; - -/** - * Handles the end events - * @ignore - */ -GridStore.prototype.end = function end(data) { - var self = this; - // allow queued data to write before closing - if(!this.writable) return; - this.writable = false; - - if(data) { - this._q.push(data); - } - - this.on('drain', function () { - self.close(function (err) { - if (err) return _error(self, err); - self.emit('close'); - }); - }); - - _flush(self); -} - -/** - * Handles the normal writes to gridstore - * @ignore - */ -var _writeNormal = function(self, data, close, callback) { - // If we have a buffer write it using the writeBuffer method - if(Buffer.isBuffer(data)) { - return writeBuffer(self, data, close, callback); - } else { - return writeBuffer(self, new Buffer(data, 'binary'), close, callback); - } -} - -/** - * Writes some data. This method will work properly only if initialized with mode "w" or "w+". - * - * @param {String|Buffer} data the data to write. - * @param {Boolean} [close] closes this file after writing if set to true. - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.write = function write(data, close, callback) { - // If it's a normal write delegate the call - if(typeof close == 'function' || typeof callback == 'function') { - return _writeNormal(this, data, close, callback); - } - - // Otherwise it's a stream write - var self = this; - if (!this.writable) { - throw new Error('GridWriteStream is not writable'); - } - - // queue data until we open. - if(!this._opened) { - // Set up a queue to save data until gridstore object is ready - this._q = []; - _openStream(self); - this._q.push(data); - return false; - } - - // Push data to queue - this._q.push(data); - _flush(this); - // Return write successful - return true; -} - -/** - * Handles the destroy part of a stream - * @ignore - */ -GridStore.prototype.destroy = function destroy() { - // close and do not emit any more events. queued data is not sent. - if(!this.writable) return; - this.readable = false; - if(this.writable) { - this.writable = false; - this._q.length = 0; - this.emit('close'); - } -} - -/** - * Handles the destroySoon part of a stream - * @ignore - */ -GridStore.prototype.destroySoon = function destroySoon() { - // as soon as write queue is drained, destroy. - // may call destroy immediately if no data is queued. - if(!this._q.length) { - return this.destroy(); - } - this._destroying = true; -} - -/** - * Handles the pipe part of the stream - * @ignore - */ -GridStore.prototype.pipe = function(destination, options) { - var self = this; - // Open the gridstore - this.open(function(err, result) { - if(err) _errorRead(self, err); - if(!self.readable) return; - // Set up the pipe - self._pipe(destination, options); - // Emit the stream is open - self.emit('open'); - // Read from the stream - _read(self); - }); - return destination; -} - -/** - * Internal module methods - * @ignore - */ -var _read = function _read(self) { - if (!self.readable || self.paused || self.reading) { - return; - } - - self.reading = true; - var stream = self._stream = self.stream(); - stream.paused = self.paused; - - stream.on('data', function (data) { - if (self._decoder) { - var str = self._decoder.write(data); - if (str.length) self.emit('data', str); - } else { - self.emit('data', data); - } - }); - - stream.on('end', function (data) { - self.emit('end', data); - }); - - stream.on('error', function (data) { - _errorRead(self, data); - }); - - stream.on('close', function (data) { - self.emit('close', data); - }); - - self.pause = function () { - // native doesn't always pause. - // bypass its pause() method to hack it - self.paused = stream.paused = true; - } - - self.resume = function () { - if(!self.paused) return; - - self.paused = false; - stream.resume(); - self.readable = stream.readable; - } - - self.destroy = function () { - self.readable = false; - stream.destroy(); - } -} - -/** - * pause - * @ignore - */ -GridStore.prototype.pause = function pause () { - // Overridden when the GridStore opens. - this.paused = true; -} - -/** - * resume - * @ignore - */ -GridStore.prototype.resume = function resume () { - // Overridden when the GridStore opens. - this.paused = false; -} - -/** - * Internal module methods - * @ignore - */ -var _flush = function _flush(self, _force) { - if (!self._opened) return; - if (!_force && self._flushing) return; - self._flushing = true; - - // write the entire q to gridfs - if (!self._q.length) { - self._flushing = false; - self.emit('drain'); - - if(self._destroying) { - self.destroy(); - } - return; - } - - self.write(self._q.shift(), function (err, store) { - if (err) return _error(self, err); - self.emit('progress', store.position); - _flush(self, true); - }); -} - -var _openStream = function _openStream (self) { - if(self._opening == true) return; - self._opening = true; - - // Open the store - self.open(function (err, gridstore) { - if (err) return _error(self, err); - self._opened = true; - self.emit('open'); - _flush(self); - }); -} - -var _error = function _error(self, err) { - self.destroy(); - self.emit('error', err); -} - -var _errorRead = function _errorRead (self, err) { - self.readable = false; - self.emit('error', err); -} - -/** - * @ignore - */ -var _hasWriteConcern = function(errorOptions) { - return errorOptions == true - || errorOptions.w > 0 - || errorOptions.w == 'majority' - || errorOptions.j == true - || errorOptions.journal == true - || errorOptions.fsync == true -} - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -/** - * @ignore - */ -var _getWriteConcern = function(self, options) { - // Final options - var finalOptions = {w:1}; - options = options || {}; - - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.options); - } else if(self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.safe); - } else if(typeof self.safe == "boolean") { - finalOptions = {w: (self.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true"); - - // Return the options - return finalOptions; -} - -/** - * @ignore - * @api private - */ -exports.GridStore = GridStore; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/gridfs/readstream.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/gridfs/readstream.js deleted file mode 100755 index 4a4f7ee3..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/gridfs/readstream.js +++ /dev/null @@ -1,206 +0,0 @@ -var Stream = require('stream').Stream, - timers = require('timers'), - util = require('util'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - * ReadStream - * - * Returns a stream interface for the **file**. - * - * Events - * - **data** {function(item) {}} the data event triggers when a document is ready. - * - **end** {function() {}} the end event triggers when there is no more documents available. - * - **close** {function() {}} the close event triggers when the stream is closed. - * - **error** {function(err) {}} the error event triggers if an error happens. - * - * @class Represents a GridFS File Stream. - * @param {Boolean} autoclose automatically close file when the stream reaches the end. - * @param {GridStore} cursor a cursor object that the stream wraps. - * @return {ReadStream} - */ -function ReadStream(autoclose, gstore) { - if (!(this instanceof ReadStream)) return new ReadStream(autoclose, gstore); - Stream.call(this); - - this.autoclose = !!autoclose; - this.gstore = gstore; - - this.finalLength = gstore.length - gstore.position; - this.completedLength = 0; - this.currentChunkNumber = gstore.currentChunk.chunkNumber; - - this.paused = false; - this.readable = true; - this.pendingChunk = null; - this.executing = false; - this.destroyed = false; - - // Calculate the number of chunks - this.numberOfChunks = Math.ceil(gstore.length/gstore.chunkSize); - - // This seek start position inside the current chunk - this.seekStartPosition = gstore.position - (this.currentChunkNumber * gstore.chunkSize); - - var self = this; - processor(function() { - self._execute(); - }); -}; - -/** - * Inherit from Stream - * @ignore - * @api private - */ -ReadStream.prototype.__proto__ = Stream.prototype; - -/** - * Flag stating whether or not this stream is readable. - */ -ReadStream.prototype.readable; - -/** - * Flag stating whether or not this stream is paused. - */ -ReadStream.prototype.paused; - -/** - * @ignore - * @api private - */ -ReadStream.prototype._execute = function() { - if(this.paused === true || this.readable === false) { - return; - } - - var gstore = this.gstore; - var self = this; - // Set that we are executing - this.executing = true; - - var last = false; - var toRead = 0; - - if(gstore.currentChunk.chunkNumber >= (this.numberOfChunks - 1)) { - self.executing = false; - last = true; - } - - // Data setup - var data = null; - - // Read a slice (with seek set if none) - if(this.seekStartPosition > 0 && (gstore.currentChunk.length() - this.seekStartPosition) > 0) { - data = gstore.currentChunk.readSlice(gstore.currentChunk.length() - this.seekStartPosition); - this.seekStartPosition = 0; - } else { - data = gstore.currentChunk.readSlice(gstore.currentChunk.length()); - } - - var processNext = function() { - if(last === true) { - self.readable = false; - self.emit("end"); - - if(self.autoclose === true) { - if(gstore.mode[0] == "w") { - gstore.close(function(err, doc) { - if (err) { - self.emit("error", err); - return; - } - self.readable = false; - self.destroyed = true; - self.emit("close", doc); - }); - } else { - self.readable = false; - self.destroyed = true; - self.emit("close"); - } - } - } else { - gstore._nthChunk(gstore.currentChunk.chunkNumber + 1, function(err, chunk) { - if(err) { - self.readable = false; - if(self.listeners("error").length > 0) - self.emit("error", err); - self.executing = false; - return; - } - - self.pendingChunk = chunk; - if(self.paused === true) { - self.executing = false; - return; - } - - gstore.currentChunk = self.pendingChunk; - self._execute(); - }); - } - } - - // Return the data - if(data != null && gstore.currentChunk.chunkNumber == self.currentChunkNumber) { - self.currentChunkNumber = self.currentChunkNumber + 1; - self.completedLength += data.length; - self.pendingChunk = null; - // Send the data - process.nextTick(function() { - self.emit("data", data); - processNext(); - }) - } else { - processNext(); - } -}; - -/** - * Pauses this stream, then no farther events will be fired. - * - * @ignore - * @api public - */ -ReadStream.prototype.pause = function() { - if(!this.executing) { - this.paused = true; - } -}; - -/** - * Destroys the stream, then no farther events will be fired. - * - * @ignore - * @api public - */ -ReadStream.prototype.destroy = function() { - if(this.destroyed) return; - this.destroyed = true; - this.readable = false; - // Emit close event - this.emit("close"); -}; - -/** - * Resumes this stream. - * - * @ignore - * @api public - */ -ReadStream.prototype.resume = function() { - if(this.paused === false || !this.readable) { - return; - } - - this.paused = false; - var self = this; - processor(function() { - self._execute(); - }); -}; - -exports.ReadStream = ReadStream; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/index.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/index.js deleted file mode 100755 index 05a4cde9..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/index.js +++ /dev/null @@ -1,62 +0,0 @@ -try { - exports.BSONPure = require('bson').BSONPure; - exports.BSONNative = require('bson').BSONNative; -} catch(err) { - // do nothing -} - -// export the driver version -exports.version = require('../../package').version; - -[ 'commands/base_command' - , 'admin' - , 'collection' - , 'connection/read_preference' - , 'connection/connection' - , 'connection/server' - , 'connection/mongos' - , 'connection/repl_set/repl_set' - , 'mongo_client' - , 'cursor' - , 'db' - , 'mongo_client' - , 'gridfs/grid' - , 'gridfs/chunk' - , 'gridfs/gridstore'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// backwards compat -exports.ReplSetServers = exports.ReplSet; -// Add BSON Classes -exports.Binary = require('bson').Binary; -exports.Code = require('bson').Code; -exports.DBRef = require('bson').DBRef; -exports.Double = require('bson').Double; -exports.Long = require('bson').Long; -exports.MinKey = require('bson').MinKey; -exports.MaxKey = require('bson').MaxKey; -exports.ObjectID = require('bson').ObjectID; -exports.Symbol = require('bson').Symbol; -exports.Timestamp = require('bson').Timestamp; -// Add BSON Parser -exports.BSON = require('bson').BSONPure.BSON; - -// Set up the connect function -var connect = exports.Db.connect; - -// Add the pure and native backward compatible functions -exports.pure = exports.native = function() { - return connect; -} - -// Map all values to the exports value -for(var name in exports) { - connect[name] = exports[name]; -} - -// Set our exports to be the connect function -module.exports = connect; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/mongo_client.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/mongo_client.js deleted file mode 100755 index 04a0fc2f..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/mongo_client.js +++ /dev/null @@ -1,482 +0,0 @@ -var Db = require('./db').Db - , Server = require('./connection/server').Server - , Mongos = require('./connection/mongos').Mongos - , ReplSet = require('./connection/repl_set/repl_set').ReplSet - , ReadPreference = require('./connection/read_preference').ReadPreference - , inherits = require('util').inherits - , EventEmitter = require('events').EventEmitter - , parse = require('./connection/url_parser').parse; - -/** - * Create a new MongoClient instance. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal - * - **j**, (Boolean, default:false) write waits for journal sync before returning - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **native_parser** {Boolean, default:false}, use c++ bson parser. - * - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **serializeFunctions** {Boolean, default:false}, serialize functions. - * - **raw** {Boolean, default:false}, peform operations using raw bson buffers. - * - **recordQueryStats** {Boolean, default:false}, record query statistics during execution. - * - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries. - * - **numberOfRetries** {Number, default:5}, number of retries off connection. - * - **bufferMaxEntries** {Boolean, default: -1}, sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * - * @class Represents a MongoClient - * @param {Object} serverConfig server config object. - * @param {Object} [options] additional options for the collection. - */ -function MongoClient(serverConfig, options) { - if(serverConfig != null) { - options = options ? options : {}; - // If no write concern is set set the default to w:1 - if('w' in options === false) { - options.w = 1; - } - - // The internal db instance we are wrapping - this._db = new Db('test', serverConfig, options); - } -} - -/** - * @ignore - */ -inherits(MongoClient, EventEmitter); - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Options - * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication - * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor** - * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor** - * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor** - * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor** - * - * @param {String} url connection url for MongoDB. - * @param {Object} [options] optional options for insert command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.prototype.connect = function(url, options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - MongoClient.connect(url, options, function(err, db) { - if(err) return callback(err, db); - // Store internal db instance reference - self._db = db; - // Emit open and perform callback - self.emit("open", err, db); - callback(err, db); - }); -} - -/** - * Initialize the database connection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the connected mongoclient or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.prototype.open = function(callback) { - // Self reference - var self = this; - // Open the db - this._db.open(function(err, db) { - if(err) return callback(err, null); - // Emit open event - self.emit("open", err, db); - // Callback - callback(null, self); - }) -} - -/** - * Close the current db connection, including all the child db instances. Emits close event and calls optional callback. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the close method or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.prototype.close = function(callback) { - this._db.close(callback); -} - -/** - * Create a new Db instance sharing the current socket connections. - * - * @param {String} dbName the name of the database we want to use. - * @return {Db} a db instance using the new database. - * @api public - */ -MongoClient.prototype.db = function(dbName) { - return this._db.db(dbName); -} - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Options - * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication - * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor** - * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor** - * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor** - * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor** - * - * @param {String} url connection url for MongoDB. - * @param {Object} [options] optional options for insert command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.connect = function(url, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] == 'function' ? args.pop() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - // Set default empty server options - var serverOptions = options.server || {}; - var mongosOptions = options.mongos || {}; - var replSetServersOptions = options.replSet || options.replSetServers || {}; - var dbOptions = options.db || {}; - - // If callback is null throw an exception - if(callback == null) - throw new Error("no callback function provided"); - - // Parse the string - var object = parse(url, options); - - // Merge in any options for db in options object - if(dbOptions) { - for(var name in dbOptions) object.db_options[name] = dbOptions[name]; - } - - // Added the url to the options - object.db_options.url = url; - - // Merge in any options for server in options object - if(serverOptions) { - for(var name in serverOptions) object.server_options[name] = serverOptions[name]; - } - - // Merge in any replicaset server options - if(replSetServersOptions) { - for(var name in replSetServersOptions) object.rs_options[name] = replSetServersOptions[name]; - } - - // Merge in any replicaset server options - if(mongosOptions) { - for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name]; - } - - // We need to ensure that the list of servers are only either direct members or mongos - // they cannot be a mix of monogs and mongod's - var totalNumberOfServers = object.servers.length; - var totalNumberOfMongosServers = 0; - var totalNumberOfMongodServers = 0; - var serverConfig = null; - var errorServers = {}; - - // Failure modes - if(object.servers.length == 0) throw new Error("connection string must contain at least one seed host"); - - // If we have no db setting for the native parser try to set the c++ one first - object.db_options.native_parser = _setNativeParser(object.db_options); - // If no auto_reconnect is set, set it to true as default for single servers - if(typeof object.server_options.auto_reconnect != 'boolean') { - object.server_options.auto_reconnect = true; - } - - // Establish the correct socketTimeout - var connectTimeoutMS = 30000; - var socketTimeoutMS = 0; - - // We have a server connection timeout setting - if(object.server_options && object.server_options.socketOptions && object.server_options.socketOptions.connectTimeoutMS) { - connectTimeoutMS = object.server_options.socketOptions.connectTimeoutMS; - } - - // We have a rs options set for connection timeout, override any server ones - if(object.rs_options && object.rs_options.socketOptions && object.rs_options.socketOptions.connectTimeoutMS) { - connectTimeoutMS = object.rs_options.socketOptions.connectTimeoutMS; - } - - // If we have no socket settings set the default values - if(object.rs_options.socketOptions.connectTimeoutMS == null) { - object.rs_options.socketOptions.connectTimeoutMS = connectTimeoutMS; - } - - if(object.rs_options.socketOptions.socketTimeoutMS == null) { - object.rs_options.socketOptions.socketTimeoutMS = socketTimeoutMS; - } - - if(object.server_options.socketOptions.connectTimeoutMS == null) { - object.server_options.socketOptions.connectTimeoutMS = connectTimeoutMS; - } - - if(object.server_options.socketOptions.socketTimeoutMS == null) { - object.server_options.socketOptions.socketTimeoutMS = socketTimeoutMS; - } - - // If we have more than a server, it could be replicaset or mongos list - // need to verify that it's one or the other and fail if it's a mix - // Connect to all servers and run ismaster - for(var i = 0; i < object.servers.length; i++) { - // Set up socket options - var _server_options = { - poolSize:1 - , socketOptions: { - connectTimeoutMS: connectTimeoutMS - , socketTimeoutMS: socketTimeoutMS - } - , auto_reconnect:false}; - - // Ensure we have ssl setup for the servers - if(object.rs_options.ssl) { - _server_options.ssl = object.rs_options.ssl; - _server_options.sslValidate = object.rs_options.sslValidate; - _server_options.sslCA = object.rs_options.sslCA; - _server_options.sslCert = object.rs_options.sslCert; - _server_options.sslKey = object.rs_options.sslKey; - _server_options.sslPass = object.rs_options.sslPass; - } else if(object.server_options.ssl) { - _server_options.ssl = object.server_options.ssl; - _server_options.sslValidate = object.server_options.sslValidate; - _server_options.sslCA = object.server_options.sslCA; - _server_options.sslCert = object.server_options.sslCert; - _server_options.sslKey = object.server_options.sslKey; - _server_options.sslPass = object.server_options.sslPass; - } - - // Set up the Server object - var _server = object.servers[i].domain_socket - ? new Server(object.servers[i].domain_socket, _server_options) - : new Server(object.servers[i].host, object.servers[i].port, _server_options); - - var connectFunction = function(__server) { - // Attempt connect - new Db(object.dbName, __server, {w:1, native_parser:false}).open(function(err, db) { - // Update number of servers - totalNumberOfServers = totalNumberOfServers - 1; - // If no error do the correct checks - if(!err) { - // Close the connection - db.close(true); - var isMasterDoc = db.serverConfig.isMasterDoc; - // Check what type of server we have - if(isMasterDoc.setName) totalNumberOfMongodServers++; - if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++; - } else { - errorServers[__server.host + ":" + __server.port] = __server; - } - - if(totalNumberOfServers == 0) { - // If we have a mix of mongod and mongos, throw an error - if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) { - return process.nextTick(function() { - try { - callback(new Error("cannot combine a list of replicaset seeds and mongos seeds")); - } catch (err) { - if(db) db.close(); - throw err - } - }) - } - - if(totalNumberOfMongodServers == 0 && object.servers.length == 1) { - var obj = object.servers[0]; - serverConfig = obj.domain_socket ? - new Server(obj.domain_socket, object.server_options) - : new Server(obj.host, obj.port, object.server_options); - } else if(totalNumberOfMongodServers > 0 || totalNumberOfMongosServers > 0) { - var finalServers = object.servers - .filter(function(serverObj) { - return errorServers[serverObj.host + ":" + serverObj.port] == null; - }) - .map(function(serverObj) { - return new Server(serverObj.host, serverObj.port, object.server_options); - }); - // Clean out any error servers - errorServers = {}; - // Set up the final configuration - if(totalNumberOfMongodServers > 0) { - serverConfig = new ReplSet(finalServers, object.rs_options); - } else { - serverConfig = new Mongos(finalServers, object.mongos_options); - } - } - - if(serverConfig == null) { - return process.nextTick(function() { - try { - callback(new Error("Could not locate any valid servers in initial seed list")); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - // Ensure no firing off open event before we are ready - serverConfig.emitOpen = false; - // Set up all options etc and connect to the database - _finishConnecting(serverConfig, object, options, callback) - } - }); - } - - // Wrap the context of the call - connectFunction(_server); - } -} - -var _setNativeParser = function(db_options) { - if(typeof db_options.native_parser == 'boolean') return db_options.native_parser; - - try { - require('bson').BSONNative.BSON; - return true; - } catch(err) { - return false; - } -} - -var _finishConnecting = function(serverConfig, object, options, callback) { - // Safe settings - var safe = {}; - // Build the safe parameter if needed - if(object.db_options.journal) safe.j = object.db_options.journal; - if(object.db_options.w) safe.w = object.db_options.w; - if(object.db_options.fsync) safe.fsync = object.db_options.fsync; - if(object.db_options.wtimeoutMS) safe.wtimeout = object.db_options.wtimeoutMS; - - // If we have a read Preference set - if(object.db_options.read_preference) { - var readPreference = new ReadPreference(object.db_options.read_preference); - // If we have the tags set up - if(object.db_options.read_preference_tags) - readPreference = new ReadPreference(object.db_options.read_preference, object.db_options.read_preference_tags); - // Add the read preference - object.db_options.readPreference = readPreference; - } - - // No safe mode if no keys - if(Object.keys(safe).length == 0) safe = false; - - // Add the safe object - object.db_options.safe = safe; - - // Get the socketTimeoutMS - var socketTimeoutMS = object.server_options.socketOptions.socketTimeoutMS || 0; - var connectTimeoutMS = object.server_options.socketOptions.connectTimeoutMS || 30000; - - // If we have a replset, override with replicaset socket timeout option if available - if(serverConfig instanceof ReplSet) { - socketTimeoutMS = object.rs_options.socketOptions.socketTimeoutMS || socketTimeoutMS; - } - - // - // Set socketTimeout to same as connectionTimeout to ensure we don't block on connect and auth - // This is a workaround for pre 2.6 servers where auth can hang when indexes are build on secondaries - serverConfig.setSocketOptions({socketTimeoutMS: connectTimeoutMS, connectTimeoutMS: connectTimeoutMS}); - - // Set up the db options - var db = new Db(object.dbName, serverConfig, object.db_options); - // Open the db - db.open(function(err, db){ - if(err) { - return process.nextTick(function() { - try { - callback(err, null); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - - // - // Set socketTimeout to same as connectionTimeout to ensure we don't block on connect and auth - // This is a workaround for pre 2.6 servers where auth can hang when indexes are build on secondaries - serverConfig.setSocketOptions({socketTimeoutMS: connectTimeoutMS, connectTimeoutMS: connectTimeoutMS}); - - // Set the provided write concern or fall back to w:1 as default - if(db.options !== null && !db.options.safe && !db.options.journal - && !db.options.w && !db.options.fsync && typeof db.options.w != 'number' - && (db.options.safe == false && object.db_options.url.indexOf("safe=") == -1)) { - db.options.w = 1; - } - - if(err == null && object.auth){ - // What db to authenticate against - var authentication_db = db; - if(object.db_options && object.db_options.authSource) { - authentication_db = db.db(object.db_options.authSource); - } - - // Build options object - var options = {}; - if(object.db_options.authMechanism) options.authMechanism = object.db_options.authMechanism; - if(object.db_options.gssapiServiceName) options.gssapiServiceName = object.db_options.gssapiServiceName; - - // Authenticate - authentication_db.authenticate(object.auth.user, object.auth.password, options, function(err, success){ - // Reset the socket timeout - serverConfig.setSocketOptions({socketTimeoutMS: socketTimeoutMS, connectTimeoutMS: connectTimeoutMS}); - - // Handle the results - if(success){ - process.nextTick(function() { - try { - callback(null, db); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } else { - if(db) db.close(); - process.nextTick(function() { - try { - callback(err ? err : new Error('Could not authenticate user ' + object.auth[0]), null); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - }); - } else { - // Reset the socket timeout - serverConfig.setSocketOptions({socketTimeoutMS: socketTimeoutMS, connectTimeoutMS: connectTimeoutMS}); - - // Return connection - process.nextTick(function() { - try { - callback(err, db); - } catch (err) { - if(db) db.close(); - throw err - } - }) - } - }); -} - -exports.MongoClient = MongoClient; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js deleted file mode 100755 index 21e8cec3..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js +++ /dev/null @@ -1,83 +0,0 @@ -var Long = require('bson').Long - , timers = require('timers'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - Reply message from mongo db -**/ -var MongoReply = exports.MongoReply = function() { - this.documents = []; - this.index = 0; -}; - -MongoReply.prototype.parseHeader = function(binary_reply, bson) { - // Unpack the standard header first - this.messageLength = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Fetch the request id for this reply - this.requestId = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Fetch the id of the request that triggered the response - this.responseTo = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - // Skip op-code field - this.index = this.index + 4 + 4; - // Unpack the reply message - this.responseFlag = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Unpack the cursor id (a 64 bit long integer) - var low_bits = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - var high_bits = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - this.cursorId = new Long(low_bits, high_bits); - // Unpack the starting from - this.startingFrom = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Unpack the number of objects returned - this.numberReturned = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; -} - -MongoReply.prototype.parseBody = function(binary_reply, bson, raw, callback) { - raw = raw == null ? false : raw; - - try { - // Let's unpack all the bson documents, deserialize them and store them - for(var object_index = 0; object_index < this.numberReturned; object_index++) { - var _options = {promoteLongs: bson.promoteLongs}; - - // Read the size of the bson object - var bsonObjectSize = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - - // If we are storing the raw responses to pipe straight through - if(raw) { - // Deserialize the object and add to the documents array - this.documents.push(binary_reply.slice(this.index, this.index + bsonObjectSize)); - } else { - // Deserialize the object and add to the documents array - this.documents.push(bson.deserialize(binary_reply.slice(this.index, this.index + bsonObjectSize), _options)); - } - - // Adjust binary index to point to next block of binary bson data - this.index = this.index + bsonObjectSize; - } - - // No error return - callback(null); - } catch(err) { - return callback(err); - } -} - -MongoReply.prototype.is_error = function(){ - if(this.documents.length == 1) { - return this.documents[0].ok == 1 ? false : true; - } - return false; -}; - -MongoReply.prototype.error_message = function() { - return this.documents.length == 1 && this.documents[0].ok == 1 ? '' : this.documents[0].errmsg; -}; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/scope.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/scope.js deleted file mode 100755 index 19ca3868..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/scope.js +++ /dev/null @@ -1,86 +0,0 @@ -var Cursor = require('./cursor').Cursor - , Readable = require('stream').Readable - , utils = require('./utils') - , inherits = require('util').inherits; - -var Scope = function(collection, _selector, _fields, _scope_options) { - var self = this; - - // Ensure we have at least an empty cursor options object - _scope_options = _scope_options || {}; - var _write_concern = _scope_options.write_concern || null; - - // Ensure default read preference - // if(!_scope_options.readPreference) _scope_options.readPreference = 'primary'; - - // Set up the cursor - var _cursor = new Cursor( - collection.db, collection, _selector - , _fields, _scope_options - ); - - // Write branch options - var writeOptions = { - insert: function(documents, callback) { - // Merge together options - var options = _write_concern || {}; - // Execute insert - collection.insert(documents, options, callback); - }, - - save: function(document, callback) { - // Merge together options - var save_options = _write_concern || {}; - // Execute save - collection.save(document, save_options, function(err, result) { - if(typeof result == 'number' && result == 1) { - return callback(null, document); - } - - return callback(null, document); - }); - }, - - find: function(selector) { - _selector = selector; - return writeOptions; - }, - - // - // Update is implicit multiple document update - update: function(operations, callback) { - // Merge together options - var update_options = _write_concern || {}; - - // Set up options, multi is default operation - update_options.multi = _scope_options.multi ? _scope_options.multi : true; - if(_scope_options.upsert) update_options.upsert = _scope_options.upsert; - - // Execute options - collection.update(_selector, operations, update_options, function(err, result, obj) { - callback(err, obj); - }); - }, - } - - // Set write concern - this.withWriteConcern = function(write_concern) { - // Save the current write concern to the Scope - _scope_options.write_concern = write_concern; - _write_concern = write_concern; - // Only allow legal options - return writeOptions; - } - - // Start find - this.find = function(selector, options) { - // Save the current selector - _selector = selector; - // Set the cursor - _cursor.selector = selector; - // Return only legal read options - return Cursor.cloneWithOptions(_cursor, _scope_options); - } -} - -exports.Scope = Scope; diff --git a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/utils.js b/server/node_modules/monk/node_modules/mongodb/lib/mongodb/utils.js deleted file mode 100755 index 656af856..00000000 --- a/server/node_modules/monk/node_modules/mongodb/lib/mongodb/utils.js +++ /dev/null @@ -1,286 +0,0 @@ -var timers = require('timers'); - -/** - * Sort functions, Normalize and prepare sort parameters - */ -var formatSortValue = exports.formatSortValue = function(sortDirection) { - var value = ("" + sortDirection).toLowerCase(); - - switch (value) { - case 'ascending': - case 'asc': - case '1': - return 1; - case 'descending': - case 'desc': - case '-1': - return -1; - default: - throw new Error("Illegal sort clause, must be of the form " - + "[['field1', '(ascending|descending)'], " - + "['field2', '(ascending|descending)']]"); - } -}; - -var formattedOrderClause = exports.formattedOrderClause = function(sortValue) { - var orderBy = {}; - if(sortValue == null) return null; - if (Array.isArray(sortValue)) { - if(sortValue.length === 0) { - return null; - } - - for(var i = 0; i < sortValue.length; i++) { - if(sortValue[i].constructor == String) { - orderBy[sortValue[i]] = 1; - } else { - orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); - } - } - } else if(sortValue != null && typeof sortValue == 'object') { - orderBy = sortValue; - } else if (typeof sortValue == 'string') { - orderBy[sortValue] = 1; - } else { - throw new Error("Illegal sort clause, must be of the form " + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); - } - - return orderBy; -}; - -exports.encodeInt = function(value) { - var buffer = new Buffer(4); - buffer[3] = (value >> 24) & 0xff; - buffer[2] = (value >> 16) & 0xff; - buffer[1] = (value >> 8) & 0xff; - buffer[0] = value & 0xff; - return buffer; -} - -exports.encodeIntInPlace = function(value, buffer, index) { - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; -} - -exports.encodeCString = function(string) { - var buf = new Buffer(string, 'utf8'); - return [buf, new Buffer([0])]; -} - -exports.decodeUInt32 = function(array, index) { - return array[index] | array[index + 1] << 8 | array[index + 2] << 16 | array[index + 3] << 24; -} - -// Decode the int -exports.decodeUInt8 = function(array, index) { - return array[index]; -} - -/** - * Context insensitive type checks - */ - -var toString = Object.prototype.toString; - -var isObject = exports.isObject = function (arg) { - return '[object Object]' == toString.call(arg) -} - -exports.isArray = function (arg) { - return Array.isArray(arg) || - 'object' == typeof arg && '[object Array]' == toString.call(arg) -} - -exports.isDate = function (arg) { - return 'object' == typeof arg && '[object Date]' == toString.call(arg) -} - -exports.isRegExp = function (arg) { - return 'object' == typeof arg && '[object RegExp]' == toString.call(arg) -} - -/** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private - */ -var toError = function(error) { - if (error instanceof Error) return error; - - var msg = error.err || error.errmsg || error.errMessage || error.$err || error; - var e = new Error(msg); - e.name = 'MongoError'; - - // Get all object keys - var keys = typeof error == 'object' - ? Object.keys(error) - : []; - - for(var i = 0; i < keys.length; i++) { - e[keys[i]] = error[keys[i]]; - } - - return e; -} -exports.toError = toError; - -/** - * Convert a single level object to an array - * @ignore - * @api private - */ -exports.objectToArray = function(object) { - var list = []; - - for(var name in object) { - list.push(object[name]) - } - - return list; -} - -/** - * Handle single command document return - * @ignore - * @api private - */ -exports.handleSingleCommandResultReturn = function(override_value_true, override_value_false, callback) { - return function(err, result, connection) { - if(callback == null) return; - if(err && typeof callback == 'function') return callback(err, null); - if(!result || !result.documents || result.documents.length == 0) - if(typeof callback == 'function') return callback(toError("command failed to return results"), null) - if(result && result.documents[0].ok == 1) { - if(override_value_true) return callback(null, override_value_true) - if(typeof callback == 'function') return callback(null, result.documents[0]); - } - - // Return the error from the document - if(typeof callback == 'function') return callback(toError(result.documents[0]), override_value_false); - } -} - -/** - * Return correct processor - * @ignore - * @api private - */ -exports.processor = function() { - // Set processor, setImmediate if 0.10 otherwise nextTick - process.maxTickDepth = Infinity; - // Only use nextTick - return process.nextTick; -} - -/** - * Allow setting the socketTimeoutMS on all connections - * to work around issues such as secondaries blocking due to compaction - * - * @ignore - * @api private - */ -exports.setSocketTimeoutProperty = function(self, options) { - Object.defineProperty(self, "socketTimeoutMS", { - enumerable: true - , get: function () { return options.socketTimeoutMS; } - , set: function (value) { - // Set the socket timeoutMS value - options.socketTimeoutMS = value; - - // Get all the connections - var connections = self.allRawConnections(); - for(var i = 0; i < connections.length; i++) { - connections[i].socketTimeoutMS = value; - } - } - }); -} - -/** - * Determine if the server supports write commands - * - * @ignore - * @api private - */ -exports.hasWriteCommands = function(connection) { - return connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasWriteCommands; -} - -/** - * Fetch server capabilities - * - * @ignore - * @api private - */ -exports.serverCapabilities = function(connection) { - return connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasWriteCommands; -} - -/** - * Create index name based on field spec - * - * @ignore - * @api private - */ -exports.parseIndexOptions = function(fieldOrSpec) { - var fieldHash = {}; - var indexes = []; - var keys; - - // Get all the fields accordingly - if('string' == typeof fieldOrSpec) { - // 'type' - indexes.push(fieldOrSpec + '_' + 1); - fieldHash[fieldOrSpec] = 1; - } else if(Array.isArray(fieldOrSpec)) { - fieldOrSpec.forEach(function(f) { - if('string' == typeof f) { - // [{location:'2d'}, 'type'] - indexes.push(f + '_' + 1); - fieldHash[f] = 1; - } else if(Array.isArray(f)) { - // [['location', '2d'],['type', 1]] - indexes.push(f[0] + '_' + (f[1] || 1)); - fieldHash[f[0]] = f[1] || 1; - } else if(isObject(f)) { - // [{location:'2d'}, {type:1}] - keys = Object.keys(f); - keys.forEach(function(k) { - indexes.push(k + '_' + f[k]); - fieldHash[k] = f[k]; - }); - } else { - // undefined (ignore) - } - }); - } else if(isObject(fieldOrSpec)) { - // {location:'2d', type:1} - keys = Object.keys(fieldOrSpec); - keys.forEach(function(key) { - indexes.push(key + '_' + fieldOrSpec[key]); - fieldHash[key] = fieldOrSpec[key]; - }); - } - - return { - name: indexes.join("_"), keys: keys, fieldHash: fieldHash - } -} - -exports.decorateCommand = function(command, options, exclude) { - for(var name in options) { - if(exclude[name] == null) command[name] = options[name]; - } - - return command; -} - -exports.shallowObjectCopy = function(object) { - var c = {}; - for(var n in object) c[n] = object[n]; - return c; -} - diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/.travis.yml b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/.travis.yml deleted file mode 100755 index 1e8f3179..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.10 # development version of 0.8, may be unstable - - 0.12 \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/HISTORY b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/HISTORY deleted file mode 100755 index 5450c140..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/HISTORY +++ /dev/null @@ -1,30 +0,0 @@ -0.2.21 2015-03-21 ------------------ -- Updated Nan to 1.7.0 to support io.js and node 0.12.0 - -0.2.19 2015-02-16 ------------------ -- Updated Nan to 1.6.2 to support io.js and node 0.12.0 - -0.2.18 2015-01-20 ------------------ -- Updated Nan to 1.5.1 to support io.js - -0.2.16 2014-12-17 ------------------ -- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's - -0.2.12 2014-08-24 ------------------ -- Fixes for fortify review of c++ extension -- toBSON correctly allows returns of non objects - -0.2.3 2013-10-01 ----------------- -- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) -- Fixed issue where corrupt CString's could cause endless loop -- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) - -0.1.4 2012-09-25 ----------------- -- Added precompiled c++ native extensions for win32 ia32 and x64 \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/LICENSE b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/LICENSE deleted file mode 100755 index 261eeb9e..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/Makefile b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/Makefile deleted file mode 100755 index 77ce4e04..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -NODE = node -NPM = npm -NODEUNIT = node_modules/nodeunit/bin/nodeunit - -all: clean node_gyp - -test: clean node_gyp - npm test - -node_gyp: clean - node-gyp configure build - -clean: - node-gyp clean - -browserify: - node_modules/.bin/onejs build browser_build/package.json browser_build/bson.js - -.PHONY: all diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/README.md b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/README.md deleted file mode 100755 index 5cac5b99..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/README.md +++ /dev/null @@ -1,69 +0,0 @@ -Javascript + C++ BSON parser -============================ - -This BSON parser is primarily meant to be used with the `mongodb` node.js driver. -However, wonderful tools such as `onejs` can package up a BSON parser that will work in the browser. -The current build is located in the `browser_build/bson.js` file. - -A simple example of how to use BSON in the browser: - -```html - - - - - - - - -``` - -A simple example of how to use BSON in `node.js`: - -```javascript -var bson = require("bson"); -var BSON = bson.BSONPure.BSON; -var Long = bson.BSONPure.Long; - -var doc = {long: Long.fromNumber(100)} - -// Serialize a document -var data = BSON.serialize(doc, false, true, false); -console.log("data:", data); - -// Deserialize the resulting Buffer -var doc_2 = BSON.deserialize(data); -console.log("doc_2:", doc_2); -``` - -The API consists of two simple methods to serialize/deserialize objects to/from BSON format: - - * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions) - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)** - * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports - - * BSON.deserialize(buffer, options, isArray) - * Options - * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * @param {TypedArray/Array} a TypedArray/Array containing the BSON data - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/binding.gyp b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/binding.gyp deleted file mode 100755 index c4455e75..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/binding.gyp +++ /dev/null @@ -1,18 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'bson', - 'sources': [ 'ext/bson.cc' ], - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'include_dirs': [ '0){ - id = pkg.modules[i].id; - - if(id==moduleId || id == moduleIndexId){ - module = pkg.modules[i]; - break; - } - } - - return module; -} - -function newRequire(callingModule){ - function require(uri){ - var module, pkg; - - if(/^\./.test(uri)){ - module = findModule(callingModule, uri); - } else if ( ties && ties.hasOwnProperty( uri ) ) { - return ties[uri]; - } else if ( aliases && aliases.hasOwnProperty( uri ) ) { - return require(aliases[uri]); - } else { - pkg = pkgmap[uri]; - - if(!pkg && nativeRequire){ - try { - pkg = nativeRequire(uri); - } catch (nativeRequireError) {} - - if(pkg) return pkg; - } - - if(!pkg){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module = pkg.index; - } - - if(!module){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module.parent = callingModule; - return module.call(); - }; - - - return require; -} - - -function module(parent, id, wrapper){ - var mod = { pkg: parent, id: id, wrapper: wrapper }, - cached = false; - - mod.exports = {}; - mod.require = newRequire(mod); - - mod.call = function(){ - if(cached) { - return mod.exports; - } - - cached = true; - - global.require = mod.require; - - mod.wrapper(mod, mod.exports, global, global.require); - return mod.exports; - }; - - if(parent.mainModuleId == mod.id){ - parent.index = mod; - parent.parents.length === 0 && ( main = mod.call ); - } - - parent.modules.push(mod); -} - -function pkg(/* [ parentId ...], wrapper */){ - var wrapper = arguments[ arguments.length - 1 ], - parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1), - ctx = wrapper(parents); - - - pkgmap[ctx.name] = ctx; - - arguments.length == 1 && ( pkgmap.main = ctx ); - - return function(modules){ - var id; - for(id in modules){ - module(ctx, id, modules[id]); - } - }; -} - - -}(this)); - -bson.pkg(function(parents){ - - return { - 'name' : 'bson', - 'mainModuleId' : 'bson', - 'modules' : [], - 'parents' : parents - }; - -})({ 'binary': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -// Binary default subtype -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - * @api private - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - * @api private - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class Represents the Binary BSON type. - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Grid} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @param {Character} byte_value a single byte we wish to write. - * @api public - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. - * @param {Number} offset specify the binary of where to write the content. - * @api public - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, 'binary', offset); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @param {Number} position read from the given position in the Binary. - * @param {Number} length the number of bytes to read. - * @return {Buffer} - * @api public - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @return {String} - * @api public - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @return {Number} the length of the binary. - * @api public - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - * @api private - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - * @api private - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -exports.Binary = Binary; - - -}, - - - -'binary_parser': function(module, exports, global, require, undefined){ - /** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; - -}, - - - -'bson': function(module, exports, global, require, undefined){ - var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class Represents the BSON Parser - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - var startIndex = index; - - switch(typeof value) { - case 'string': - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] || true; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00) { i++ } - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; - -}, - - - -'code': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Code type. - * - * @class Represents the BSON Code type. - * @param {String|Function} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - * @api private - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -exports.Code = Code; -}, - - - -'db_ref': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON DBRef type. - * - * @class Represents the BSON DBRef type. - * @param {String} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {String} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -exports.DBRef = DBRef; -}, - - - -'double': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Double type. - * - * @class Represents the BSON Double type. - * @param {Number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @return {Number} returns the wrapped double number. - * @api public - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Double.prototype.toJSON = function() { - return this.value; -} - -exports.Double = Double; -}, - - - -'float_parser': function(module, exports, global, require, undefined){ - // Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; -}, - - - -'index': function(module, exports, global, require, undefined){ - try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('../../ext'); -} catch(err) { - // do nothing -} - -[ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '../../ext' -].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -}, - - - -'long': function(module, exports, global, require, undefined){ - // Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Long type. - * @param {Number} low the low (signed) 32 bits of the Long. - * @param {Number} high the high (signed) 32 bits of the Long. - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. - * @api public - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long equals the other - * @api public - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long does not equal the other. - * @api public - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than the other. - * @api public - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than or equal to the other. - * @api public - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than the other. - * @api public - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than or equal to the other. - * @api public - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @param {Long} other Long to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Long} the negation of this value. - * @api public - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - * @api public - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - * @api public - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - * @api public - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - * @api public - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - * @api public - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Long} the bitwise-NOT of this value. - * @api public - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - * @api public - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - * @api public - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - * @api public - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - * @api public - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - * @api public - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Long. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @api private - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @api private - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Long = Long; -}, - - - -'max_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MaxKey type. - * - * @class Represents the BSON MaxKey type. - * @return {MaxKey} - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -exports.MaxKey = MaxKey; -}, - - - -'min_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MinKey type. - * - * @class Represents the BSON MinKey type. - * @return {MinKey} - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -exports.MinKey = MinKey; -}, - - - -'objectid': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class Represents the BSON ObjectID type -* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @return {Object} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id, _hex) { - if(!(this instanceof ObjectID)) return new ObjectID(id, _hex); - - this._bsontype = 'ObjectID'; - var __id = null; - - // Throw an error if it's not a valid setup - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - // Generate id based on the input - if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if(checkForHexRegExp.test(id)) { - return ObjectID.createFromHexString(id); - } else { - throw new Error("Value passed in is not a valid 24 character hex string"); - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId as well as ObjectID -var ObjectId = ObjectID; - -// Precomputed hex table enables speedy hex string conversion -var hexTable = []; -for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); -} - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @return {String} return the 24 byte hex string representation. -* @api public -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {String} return the 12 byte id binary string. -* @api private -*/ -ObjectID.prototype.generate = function(time) { - if ('number' == typeof time) { - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } else { - var unixTime = parseInt(Date.now()/1000,10); - var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true); - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @param {Object} otherID ObjectID instance to compare against. -* @return {Bool} the result of comparing two ObjectID's -* @api public -*/ -ObjectID.prototype.equals = function equals (otherID) { - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @return {Date} the generation date -* @api public -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -* @api private -*/ -ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); - -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @param {Number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -exports.ObjectID = ObjectID; -exports.ObjectId = ObjectID; - -}, - - - -'symbol': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Symbol type. - * - * @class Represents the BSON Symbol type. - * @param {String} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @return {String} returns the wrapped string. - * @api public - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -exports.Symbol = Symbol; -}, - - - -'timestamp': function(module, exports, global, require, undefined){ - // Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Timestamp type. - * @param {Number} low the low (signed) 32 bits of the Timestamp. - * @param {Number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. - * @api public - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp equals the other - * @api public - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp does not equal the other. - * @api public - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than the other. - * @api public - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than or equal to the other. - * @api public - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than the other. - * @api public - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than or equal to the other. - * @api public - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Timestamp} the negation of this value. - * @api public - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - * @api public - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - * @api public - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - * @api public - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Timestamp} the bitwise-NOT of this value. - * @api public - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - * @api public - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - * @api public - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - * @api public - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - * @api public - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - * @api public - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Timestamp. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @api private - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @api private - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Timestamp = Timestamp; -}, - - }); - - -if(typeof module != 'undefined' && module.exports ){ - module.exports = bson; - - if( !module.parent ){ - bson(); - } -} - -if(typeof window != 'undefined' && typeof require == 'undefined'){ - window.require = bson.require; -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/browser_build/package.json b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/browser_build/package.json deleted file mode 100755 index 3ebb5876..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../lib/bson/bson" -, "directories" : { "lib" : "../lib/bson" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : [ { "type" : "Apache License, Version 2.0" - , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Makefile b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Makefile deleted file mode 100755 index 97960c0a..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Makefile +++ /dev/null @@ -1,332 +0,0 @@ -# We borrow heavily from the kernel build setup, though we are simpler since -# we don't have Kconfig tweaking settings on us. - -# The implicit make rules have it looking for RCS files, among other things. -# We instead explicitly write all the rules we care about. -# It's even quicker (saves ~200ms) to pass -r on the command line. -MAKEFLAGS=-r - -# The source directory tree. -srcdir := .. -abs_srcdir := $(abspath $(srcdir)) - -# The name of the builddir. -builddir_name ?= . - -# The V=1 flag on command line makes us verbosely print command lines. -ifdef V - quiet= -else - quiet=quiet_ -endif - -# Specify BUILDTYPE=Release on the command line for a release build. -BUILDTYPE ?= Release - -# Directory all our build output goes into. -# Note that this must be two directories beneath src/ for unit tests to pass, -# as they reach into the src/ directory for data with relative paths. -builddir ?= $(builddir_name)/$(BUILDTYPE) -abs_builddir := $(abspath $(builddir)) -depsdir := $(builddir)/.deps - -# Object output directory. -obj := $(builddir)/obj -abs_obj := $(abspath $(obj)) - -# We build up a list of every single one of the targets so we can slurp in the -# generated dependency rule Makefiles in one pass. -all_deps := - - - -CC.target ?= $(CC) -CFLAGS.target ?= $(CFLAGS) -CXX.target ?= $(CXX) -CXXFLAGS.target ?= $(CXXFLAGS) -LINK.target ?= $(LINK) -LDFLAGS.target ?= $(LDFLAGS) -AR.target ?= $(AR) - -# C++ apps need to be linked with g++. -# -# Note: flock is used to seralize linking. Linking is a memory-intensive -# process so running parallel links can often lead to thrashing. To disable -# the serialization, override LINK via an envrionment variable as follows: -# -# export LINK=g++ -# -# This will allow make to invoke N linker processes as specified in -jN. -LINK ?= flock $(builddir)/linker.lock $(CXX.target) - -# TODO(evan): move all cross-compilation logic to gyp-time so we don't need -# to replicate this environment fallback in make as well. -CC.host ?= gcc -CFLAGS.host ?= -CXX.host ?= g++ -CXXFLAGS.host ?= -LINK.host ?= $(CXX.host) -LDFLAGS.host ?= -AR.host ?= ar - -# Define a dir function that can handle spaces. -# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions -# "leading spaces cannot appear in the text of the first argument as written. -# These characters can be put into the argument value by variable substitution." -empty := -space := $(empty) $(empty) - -# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces -replace_spaces = $(subst $(space),?,$1) -unreplace_spaces = $(subst ?,$(space),$1) -dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) - -# Flags to make gcc output dependency info. Note that you need to be -# careful here to use the flags that ccache and distcc can understand. -# We write to a dep file on the side first and then rename at the end -# so we can't end up with a broken dep file. -depfile = $(depsdir)/$(call replace_spaces,$@).d -DEPFLAGS = -MMD -MF $(depfile).raw - -# We have to fixup the deps output in a few ways. -# (1) the file output should mention the proper .o file. -# ccache or distcc lose the path to the target, so we convert a rule of -# the form: -# foobar.o: DEP1 DEP2 -# into -# path/to/foobar.o: DEP1 DEP2 -# (2) we want missing files not to cause us to fail to build. -# We want to rewrite -# foobar.o: DEP1 DEP2 \ -# DEP3 -# to -# DEP1: -# DEP2: -# DEP3: -# so if the files are missing, they're just considered phony rules. -# We have to do some pretty insane escaping to get those backslashes -# and dollar signs past make, the shell, and sed at the same time. -# Doesn't work with spaces, but that's fine: .d files have spaces in -# their names replaced with other characters. -define fixup_dep -# The depfile may not exist if the input file didn't have any #includes. -touch $(depfile).raw -# Fixup path as in (1). -sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = AR($(TOOLSET)) $@ -cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) - -quiet_cmd_alink_thin = AR($(TOOLSET)) $@ -cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) - -# Due to circular dependencies between libraries :(, we wrap the -# special "figure out circular dependencies" flags around the entire -# input list during linking. -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) - -# We support two kinds of shared objects (.so): -# 1) shared_library, which is just bundling together many dependent libraries -# into a link line. -# 2) loadable_module, which is generating a module intended for dlopen(). -# -# They differ only slightly: -# In the former case, we want to package all dependent code into the .so. -# In the latter case, we want to package just the API exposed by the -# outermost module. -# This means shared_library uses --whole-archive, while loadable_module doesn't. -# (Note that --whole-archive is incompatible with the --start-group used in -# normal linking.) - -# Other shared-object link notes: -# - Set SONAME to the library filename so our binaries don't reference -# the local, absolute paths used on the link command-line. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) - -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 1,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,bson.target.mk)))),) - include bson.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /usr/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/var/www/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/config.gypi -I/usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/kasperrt/.node-gyp/0.10.33/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/kasperrt/.node-gyp/0.10.33" "-Dmodule_root_dir=/var/www/server/node_modules/monk/node_modules/mongodb/node_modules/bson" binding.gyp -Makefile: $(srcdir)/../../../../../../../../../home/kasperrt/.node-gyp/0.10.33/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d deleted file mode 100755 index 866c155b..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/bson.node := rm -rf "Release/bson.node" && cp -af "Release/obj.target/bson.node" "Release/bson.node" diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson.node.d b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson.node.d deleted file mode 100755 index 20f49008..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/obj.target/bson.node := flock ./Release/linker.lock g++ -shared -pthread -rdynamic -m64 -Wl,-soname=bson.node -o Release/obj.target/bson.node -Wl,--start-group Release/obj.target/bson/ext/bson.o -Wl,--end-group diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d deleted file mode 100755 index 59aa1ef9..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d +++ /dev/null @@ -1,33 +0,0 @@ -cmd_Release/obj.target/bson/ext/bson.o := g++ '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/kasperrt/.node-gyp/0.10.33/src -I/home/kasperrt/.node-gyp/0.10.33/deps/uv/include -I/home/kasperrt/.node-gyp/0.10.33/deps/v8/include -I../node_modules/nan -fPIC -Wall -Wextra -Wno-unused-parameter -pthread -m64 -O2 -fno-strict-aliasing -fno-tree-vrp -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/bson/ext/bson.o.d.raw -c -o Release/obj.target/bson/ext/bson.o ../ext/bson.cc -Release/obj.target/bson/ext/bson.o: ../ext/bson.cc \ - /home/kasperrt/.node-gyp/0.10.33/deps/v8/include/v8.h \ - /home/kasperrt/.node-gyp/0.10.33/deps/v8/include/v8stdint.h \ - /home/kasperrt/.node-gyp/0.10.33/src/node.h \ - /home/kasperrt/.node-gyp/0.10.33/deps/uv/include/uv.h \ - /home/kasperrt/.node-gyp/0.10.33/deps/uv/include/uv-private/uv-unix.h \ - /home/kasperrt/.node-gyp/0.10.33/deps/uv/include/uv-private/ngx-queue.h \ - /home/kasperrt/.node-gyp/0.10.33/deps/uv/include/uv-private/uv-linux.h \ - /home/kasperrt/.node-gyp/0.10.33/src/node_object_wrap.h \ - /home/kasperrt/.node-gyp/0.10.33/src/node.h \ - /home/kasperrt/.node-gyp/0.10.33/src/node_version.h \ - /home/kasperrt/.node-gyp/0.10.33/src/node_buffer.h ../ext/bson.h \ - /home/kasperrt/.node-gyp/0.10.33/src/node_object_wrap.h \ - ../node_modules/nan/nan.h ../node_modules/nan/nan_new.h \ - ../node_modules/nan/nan_implementation_pre_12_inl.h -../ext/bson.cc: -/home/kasperrt/.node-gyp/0.10.33/deps/v8/include/v8.h: -/home/kasperrt/.node-gyp/0.10.33/deps/v8/include/v8stdint.h: -/home/kasperrt/.node-gyp/0.10.33/src/node.h: -/home/kasperrt/.node-gyp/0.10.33/deps/uv/include/uv.h: -/home/kasperrt/.node-gyp/0.10.33/deps/uv/include/uv-private/uv-unix.h: -/home/kasperrt/.node-gyp/0.10.33/deps/uv/include/uv-private/ngx-queue.h: -/home/kasperrt/.node-gyp/0.10.33/deps/uv/include/uv-private/uv-linux.h: -/home/kasperrt/.node-gyp/0.10.33/src/node_object_wrap.h: -/home/kasperrt/.node-gyp/0.10.33/src/node.h: -/home/kasperrt/.node-gyp/0.10.33/src/node_version.h: -/home/kasperrt/.node-gyp/0.10.33/src/node_buffer.h: -../ext/bson.h: -/home/kasperrt/.node-gyp/0.10.33/src/node_object_wrap.h: -../node_modules/nan/nan.h: -../node_modules/nan/nan_new.h: -../node_modules/nan/nan_implementation_pre_12_inl.h: diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/bson.node b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/bson.node deleted file mode 100755 index d5ac34d1..00000000 Binary files a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/bson.node and /dev/null differ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/linker.lock b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/linker.lock deleted file mode 100755 index e69de29b..00000000 diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson.node b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson.node deleted file mode 100755 index d5ac34d1..00000000 Binary files a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson.node and /dev/null differ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o deleted file mode 100755 index b219b50a..00000000 Binary files a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o and /dev/null differ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/binding.Makefile b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/binding.Makefile deleted file mode 100755 index d7430e6d..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= ./build/. -.PHONY: all -all: - $(MAKE) bson diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/bson.target.mk b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/bson.target.mk deleted file mode 100755 index 1839d09b..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/bson.target.mk +++ /dev/null @@ -1,130 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := bson -DEFS_Debug := \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -fPIC \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -pthread \ - -m64 \ - -g \ - -O0 - -# Flags passed to only C files. -CFLAGS_C_Debug := - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti - -INCS_Debug := \ - -I/home/kasperrt/.node-gyp/0.10.33/src \ - -I/home/kasperrt/.node-gyp/0.10.33/deps/uv/include \ - -I/home/kasperrt/.node-gyp/0.10.33/deps/v8/include \ - -I$(srcdir)/node_modules/nan - -DEFS_Release := \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -fPIC \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -pthread \ - -m64 \ - -O2 \ - -fno-strict-aliasing \ - -fno-tree-vrp \ - -fno-omit-frame-pointer - -# Flags passed to only C files. -CFLAGS_C_Release := - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti - -INCS_Release := \ - -I/home/kasperrt/.node-gyp/0.10.33/src \ - -I/home/kasperrt/.node-gyp/0.10.33/deps/uv/include \ - -I/home/kasperrt/.node-gyp/0.10.33/deps/v8/include \ - -I$(srcdir)/node_modules/nan - -OBJS := \ - $(obj).target/$(TARGET)/ext/bson.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -pthread \ - -rdynamic \ - -m64 - -LDFLAGS_Release := \ - -pthread \ - -rdynamic \ - -m64 - -LIBS := - -$(obj).target/bson.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(obj).target/bson.node: LIBS := $(LIBS) -$(obj).target/bson.node: TOOLSET := $(TOOLSET) -$(obj).target/bson.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(obj).target/bson.node -# Add target alias -.PHONY: bson -bson: $(builddir)/bson.node - -# Copy this to the executable output path. -$(builddir)/bson.node: TOOLSET := $(TOOLSET) -$(builddir)/bson.node: $(obj).target/bson.node FORCE_DO_CMD - $(call do_cmd,copy) - -all_deps += $(builddir)/bson.node -# Short alias for building this executable. -.PHONY: bson.node -bson.node: $(obj).target/bson.node $(builddir)/bson.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/bson.node - diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/config.gypi b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/config.gypi deleted file mode 100755 index 5a02ae8b..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build/config.gypi +++ /dev/null @@ -1,122 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "clang": 0, - "gcc_version": 46, - "host_arch": "x64", - "node_install_npm": "true", - "node_prefix": "/usr", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_openssl": "false", - "node_shared_v8": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_unsafe_optimizations": 0, - "node_use_dtrace": "false", - "node_use_etw": "false", - "node_use_openssl": "true", - "node_use_perfctr": "false", - "node_use_systemtap": "false", - "openssl_no_asm": 0, - "python": "/usr/bin/python", - "target_arch": "x64", - "v8_enable_gdbjit": 0, - "v8_no_strict_aliasing": 1, - "v8_use_snapshot": "false", - "want_separate_host_toolset": 0, - "nodedir": "/home/kasperrt/.node-gyp/0.10.33", - "copy_dev_lib": "true", - "standalone_static_library": 1, - "cache_lock_stale": "60000", - "sign_git_tag": "", - "user_agent": "npm/1.4.28 node/v0.10.33 linux x64", - "always_auth": "", - "bin_links": "true", - "key": "", - "description": "true", - "fetch_retries": "2", - "heading": "npm", - "user": "1000", - "force": "", - "cache_min": "10", - "init_license": "ISC", - "editor": "vi", - "rollback": "true", - "cache_max": "Infinity", - "userconfig": "/home/kasperrt/.npmrc", - "engine_strict": "", - "init_author_name": "", - "init_author_url": "", - "tmp": "/tmp", - "depth": "Infinity", - "save_dev": "", - "usage": "", - "cafile": "", - "https_proxy": "", - "onload_script": "", - "rebuild_bundle": "true", - "save_bundle": "", - "shell": "/bin/zsh", - "prefix": "/usr", - "registry": "https://registry.npmjs.org/", - "browser": "", - "cache_lock_wait": "10000", - "save_optional": "", - "searchopts": "", - "versions": "", - "cache": "/home/kasperrt/.npm", - "ignore_scripts": "", - "searchsort": "name", - "version": "", - "local_address": "", - "viewer": "man", - "color": "true", - "fetch_retry_mintimeout": "10000", - "umask": "18", - "fetch_retry_maxtimeout": "60000", - "message": "%s", - "ca": "", - "cert": "", - "global": "", - "link": "", - "save": "", - "unicode": "true", - "long": "", - "production": "", - "unsafe_perm": "", - "node_version": "0.10.33", - "tag": "latest", - "git_tag_version": "true", - "shrinkwrap": "true", - "fetch_retry_factor": "10", - "npat": "", - "proprietary_attribs": "true", - "save_exact": "", - "strict_ssl": "true", - "username": "", - "dev": "", - "globalconfig": "/usr/etc/npmrc", - "init_module": "/home/kasperrt/.npm-init.js", - "parseable": "", - "globalignorefile": "/usr/etc/npmignore", - "cache_lock_retries": "10", - "save_prefix": "^", - "group": "1000", - "init_author_email": "", - "searchexclude": "", - "git": "git", - "optional": "true", - "email": "", - "json": "", - "spin": "true" - } -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build_browser.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build_browser.js deleted file mode 100755 index bb802384..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/build_browser.js +++ /dev/null @@ -1,7 +0,0 @@ -require('one'); - -one('./package.json') - .tie('bson', BSON) - // .exclude('buffer') - .tie('buffer', {}) - .save('./browser_build/bson.js') \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/builderror.log b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/builderror.log deleted file mode 100755 index e69de29b..00000000 diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/Makefile b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/Makefile deleted file mode 100755 index 435999ee..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -NODE = node -name = all -JOBS = 1 - -all: - rm -rf build .lock-wscript bson.node - node-waf configure build - cp -R ./build/Release/bson.node . || true - -all_debug: - rm -rf build .lock-wscript bson.node - node-waf --debug configure build - cp -R ./build/Release/bson.node . || true - -clang: - rm -rf build .lock-wscript bson.node - CXX=clang node-waf configure build - cp -R ./build/Release/bson.node . || true - -clang_debug: - rm -rf build .lock-wscript bson.node - CXX=clang node-waf --debug configure build - cp -R ./build/Release/bson.node . || true - -clean: - rm -rf build .lock-wscript bson.node - -.PHONY: all \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/bson.cc b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/bson.cc deleted file mode 100755 index 90e2ef9b..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/bson.cc +++ /dev/null @@ -1,1072 +0,0 @@ -//=========================================================================== - -#include -#include -#include -#include -#include - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-parameter" -#endif - -#include - -// this and the above block must be around the v8.h header otherwise -// v8 is not happy -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#include -#include -#include - -#include -#include -#include -#include -#include - -#if defined(__sun) || defined(_AIX) - #include -#endif - -#include "bson.h" - -using namespace v8; -using namespace node; - -void die(const char *message) { - if(errno) { - perror(message); - } else { - printf("ERROR: %s\n", message); - } - - exit(1); -} - -//=========================================================================== - -void DataStream::WriteObjectId(const Handle& object, const Handle& key) -{ - uint16_t buffer[12]; - object->Get(key)->ToString()->Write(buffer, 0, 12); - for(uint32_t i = 0; i < 12; ++i) - { - *p++ = (char) buffer[i]; - } -} - -void ThrowAllocatedStringException(size_t allocationSize, const char* format, ...) -{ - va_list args; - va_start(args, format); - char* string = (char*) malloc(allocationSize); - if(string == NULL) die("Failed to allocate ThrowAllocatedStringException"); - vsprintf(string, format, args); - va_end(args); - throw string; -} - -void DataStream::CheckKey(const Local& keyName) -{ - size_t keyLength = keyName->Utf8Length(); - if(keyLength == 0) return; - - // Allocate space for the key, do not need to zero terminate as WriteUtf8 does it - char* keyStringBuffer = (char*) alloca(keyLength + 1); - // Write the key to the allocated buffer - keyName->WriteUtf8(keyStringBuffer); - // Check for the zero terminator - char* terminator = strchr(keyStringBuffer, 0x00); - - // If the location is not at the end of the string we've got an illegal 0x00 byte somewhere - if(terminator != &keyStringBuffer[keyLength]) { - ThrowAllocatedStringException(64+keyLength, "key %s must not contain null bytes", keyStringBuffer); - } - - if(keyStringBuffer[0] == '$') - { - ThrowAllocatedStringException(64+keyLength, "key %s must not start with '$'", keyStringBuffer); - } - - if(strchr(keyStringBuffer, '.') != NULL) - { - ThrowAllocatedStringException(64+keyLength, "key %s must not contain '.'", keyStringBuffer); - } -} - -template void BSONSerializer::SerializeDocument(const Handle& value) -{ - void* documentSize = this->BeginWriteSize(); - Local object = bson->GetSerializeObject(value); - - // Get the object property names - Local propertyNames = object->GetPropertyNames(); - - // Length of the property - int propertyLength = propertyNames->Length(); - for(int i = 0; i < propertyLength; ++i) - { - const Local& propertyName = propertyNames->Get(i)->ToString(); - if(checkKeys) this->CheckKey(propertyName); - - const Local& propertyValue = object->Get(propertyName); - - if(serializeFunctions || !propertyValue->IsFunction()) - { - void* typeLocation = this->BeginWriteType(); - this->WriteString(propertyName); - SerializeValue(typeLocation, propertyValue); - } - } - - this->WriteByte(0); - this->CommitSize(documentSize); -} - -template void BSONSerializer::SerializeArray(const Handle& value) -{ - void* documentSize = this->BeginWriteSize(); - - Local array = Local::Cast(value->ToObject()); - uint32_t arrayLength = array->Length(); - - for(uint32_t i = 0; i < arrayLength; ++i) - { - void* typeLocation = this->BeginWriteType(); - this->WriteUInt32String(i); - SerializeValue(typeLocation, array->Get(i)); - } - - this->WriteByte(0); - this->CommitSize(documentSize); -} - -// This is templated so that we can use this function to both count the number of bytes, and to serialize those bytes. -// The template approach eliminates almost all of the inspection of values unless they're required (eg. string lengths) -// and ensures that there is always consistency between bytes counted and bytes written by design. -template void BSONSerializer::SerializeValue(void* typeLocation, const Handle constValue) -{ - // Turn into local value - Local value = NanNew(constValue); - - // Check for toBSON function - if(value->IsObject()) { - Local object = value->ToObject(); - - // NanNew("toBSON") - // NanNew(BSON::_toBSONString) - - if(object->Has(NanNew("toBSON"))) { - const Local& toBSON = object->Get(NanNew("toBSON")); - if(!toBSON->IsFunction()) ThrowAllocatedStringException(64, "toBSON is not a function"); - value = Local::Cast(toBSON)->Call(object, 0, NULL); - } - } - - // Process all the values - if(value->IsNumber()) - { - double doubleValue = value->NumberValue(); - int intValue = (int) doubleValue; - if(intValue == doubleValue) - { - this->CommitType(typeLocation, BSON_TYPE_INT); - this->WriteInt32(intValue); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_NUMBER); - this->WriteDouble(doubleValue); - } - } - else if(value->IsString()) - { - this->CommitType(typeLocation, BSON_TYPE_STRING); - this->WriteLengthPrefixedString(value->ToString()); - } - else if(value->IsBoolean()) - { - this->CommitType(typeLocation, BSON_TYPE_BOOLEAN); - this->WriteBool(value); - } - else if(value->IsArray()) - { - this->CommitType(typeLocation, BSON_TYPE_ARRAY); - SerializeArray(value); - } - else if(value->IsDate()) - { - this->CommitType(typeLocation, BSON_TYPE_DATE); - this->WriteInt64(value); - } - else if(value->IsRegExp()) - { - this->CommitType(typeLocation, BSON_TYPE_REGEXP); - const Handle& regExp = Handle::Cast(value); - - this->WriteString(regExp->GetSource()); - - int flags = regExp->GetFlags(); - if(flags & RegExp::kGlobal) this->WriteByte('s'); - if(flags & RegExp::kIgnoreCase) this->WriteByte('i'); - if(flags & RegExp::kMultiline) this->WriteByte('m'); - this->WriteByte(0); - } - else if(value->IsFunction()) - { - this->CommitType(typeLocation, BSON_TYPE_CODE); - this->WriteLengthPrefixedString(value->ToString()); - } - else if(value->IsObject()) - { - const Local& object = value->ToObject(); - if(object->Has(NanNew(bson->_bsontypeString))) - { - const Local& constructorString = object->Get(NanNew(bson->_bsontypeString))->ToString(); - if(NanNew(bson->longString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_LONG); - this->WriteInt32(object, NanNew(bson->_longLowString)); - this->WriteInt32(object, NanNew(bson->_longHighString)); - } - else if(NanNew(bson->timestampString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_TIMESTAMP); - this->WriteInt32(object, NanNew(bson->_longLowString)); - this->WriteInt32(object, NanNew(bson->_longHighString)); - } - else if(NanNew(bson->objectIDString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_OID); - this->WriteObjectId(object, NanNew(bson->_objectIDidString)); - } - else if(NanNew(bson->binaryString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_BINARY); - - uint32_t length = object->Get(NanNew(bson->_binaryPositionString))->Uint32Value(); - Local bufferObj = object->Get(NanNew(bson->_binaryBufferString))->ToObject(); - - this->WriteInt32(length); - this->WriteByte(object, NanNew(bson->_binarySubTypeString)); // write subtype - // If type 0x02 write the array length aswell - if(object->Get(NanNew(bson->_binarySubTypeString))->Int32Value() == 0x02) { - this->WriteInt32(length); - } - // Write the actual data - this->WriteData(Buffer::Data(bufferObj), length); - } - else if(NanNew(bson->doubleString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_NUMBER); - this->WriteDouble(object, NanNew(bson->_doubleValueString)); - } - else if(NanNew(bson->symbolString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_SYMBOL); - this->WriteLengthPrefixedString(object->Get(NanNew(bson->_symbolValueString))->ToString()); - } - else if(NanNew(bson->codeString)->StrictEquals(constructorString)) - { - const Local& function = object->Get(NanNew(bson->_codeCodeString))->ToString(); - const Local& scope = object->Get(NanNew(bson->_codeScopeString))->ToObject(); - - // For Node < 0.6.X use the GetPropertyNames - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 - uint32_t propertyNameLength = scope->GetPropertyNames()->Length(); - #else - uint32_t propertyNameLength = scope->GetOwnPropertyNames()->Length(); - #endif - - if(propertyNameLength > 0) - { - this->CommitType(typeLocation, BSON_TYPE_CODE_W_SCOPE); - void* codeWidthScopeSize = this->BeginWriteSize(); - this->WriteLengthPrefixedString(function->ToString()); - SerializeDocument(scope); - this->CommitSize(codeWidthScopeSize); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_CODE); - this->WriteLengthPrefixedString(function->ToString()); - } - } - else if(NanNew(bson->dbrefString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_OBJECT); - - void* dbRefSize = this->BeginWriteSize(); - - void* refType = this->BeginWriteType(); - this->WriteData("$ref", 5); - SerializeValue(refType, object->Get(NanNew(bson->_dbRefNamespaceString))); - - void* idType = this->BeginWriteType(); - this->WriteData("$id", 4); - SerializeValue(idType, object->Get(NanNew(bson->_dbRefOidString))); - - const Local& refDbValue = object->Get(NanNew(bson->_dbRefDbString)); - if(!refDbValue->IsUndefined()) - { - void* dbType = this->BeginWriteType(); - this->WriteData("$db", 4); - SerializeValue(dbType, refDbValue); - } - - this->WriteByte(0); - this->CommitSize(dbRefSize); - } - else if(NanNew(bson->minKeyString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_MIN_KEY); - } - else if(NanNew(bson->maxKeyString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_MAX_KEY); - } - } - else if(Buffer::HasInstance(value)) - { - this->CommitType(typeLocation, BSON_TYPE_BINARY); - - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Local buffer = ObjectWrap::Unwrap(value->ToObject()); - uint32_t length = object->length(); - #else - uint32_t length = Buffer::Length(value->ToObject()); - #endif - - this->WriteInt32(length); - this->WriteByte(0); - this->WriteData(Buffer::Data(value->ToObject()), length); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_OBJECT); - SerializeDocument(value); - } - } - else if(value->IsNull() || value->IsUndefined()) - { - this->CommitType(typeLocation, BSON_TYPE_NULL); - } -} - -// Data points to start of element list, length is length of entire document including '\0' but excluding initial size -BSONDeserializer::BSONDeserializer(BSON* aBson, char* data, size_t length) -: bson(aBson), - pStart(data), - p(data), - pEnd(data + length - 1) -{ - if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); -} - -BSONDeserializer::BSONDeserializer(BSONDeserializer& parentSerializer, size_t length) -: bson(parentSerializer.bson), - pStart(parentSerializer.p), - p(parentSerializer.p), - pEnd(parentSerializer.p + length - 1) -{ - parentSerializer.p += length; - if(pEnd > parentSerializer.pEnd) ThrowAllocatedStringException(64, "Child document exceeds parent's bounds"); - if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); -} - -Handle BSONDeserializer::ReadCString() -{ - char* start = p; - while(*p++ && (p < pEnd)) { } - if(p > pEnd) { - return NanNull(); - } - return NanNew(start, (int32_t) (p-start-1) ); -} - -int32_t BSONDeserializer::ReadRegexOptions() -{ - int32_t options = 0; - for(;;) - { - switch(*p++) - { - case '\0': return options; - case 's': options |= RegExp::kGlobal; break; - case 'i': options |= RegExp::kIgnoreCase; break; - case 'm': options |= RegExp::kMultiline; break; - } - } -} - -uint32_t BSONDeserializer::ReadIntegerString() -{ - uint32_t value = 0; - while(*p) - { - if(*p < '0' || *p > '9') ThrowAllocatedStringException(64, "Invalid key for array"); - value = value * 10 + *p++ - '0'; - } - ++p; - return value; -} - -Local BSONDeserializer::ReadString() -{ - uint32_t length = ReadUInt32(); - char* start = p; - p += length; - return NanNew(start, length-1); -} - -Local BSONDeserializer::ReadObjectId() -{ - uint16_t objectId[12]; - for(size_t i = 0; i < 12; ++i) - { - objectId[i] = *reinterpret_cast(p++); - } - return NanNew(objectId, 12); -} - -Handle BSONDeserializer::DeserializeDocument(bool promoteLongs) -{ - uint32_t length = ReadUInt32(); - if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Document is less than 5 bytes"); - - BSONDeserializer documentDeserializer(*this, length-4); - return documentDeserializer.DeserializeDocumentInternal(promoteLongs); -} - -Handle BSONDeserializer::DeserializeDocumentInternal(bool promoteLongs) -{ - Local returnObject = NanNew(); - - while(HasMoreData()) - { - BsonType type = (BsonType) ReadByte(); - const Handle& name = ReadCString(); - if(name->IsNull()) ThrowAllocatedStringException(64, "Bad BSON Document: illegal CString"); - // name->Is - const Handle& value = DeserializeValue(type, promoteLongs); - returnObject->ForceSet(name, value); - } - if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Document: Serialize consumed unexpected number of bytes"); - - // From JavaScript: - // if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - if(returnObject->Has(NanNew(bson->_dbRefIdRefString))) - { - Local argv[] = { returnObject->Get(NanNew(bson->_dbRefRefString)), returnObject->Get(NanNew(bson->_dbRefIdRefString)), returnObject->Get(NanNew(bson->_dbRefDbRefString)) }; - return NanNew(bson->dbrefConstructor)->NewInstance(3, argv); - } - else - { - return returnObject; - } -} - -Handle BSONDeserializer::DeserializeArray(bool promoteLongs) -{ - uint32_t length = ReadUInt32(); - if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Array Document is less than 5 bytes"); - - BSONDeserializer documentDeserializer(*this, length-4); - return documentDeserializer.DeserializeArrayInternal(promoteLongs); -} - -Handle BSONDeserializer::DeserializeArrayInternal(bool promoteLongs) -{ - Local returnArray = NanNew(); - - while(HasMoreData()) - { - BsonType type = (BsonType) ReadByte(); - uint32_t index = ReadIntegerString(); - const Handle& value = DeserializeValue(type, promoteLongs); - returnArray->Set(index, value); - } - if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Array: Serialize consumed unexpected number of bytes"); - - return returnArray; -} - -Handle BSONDeserializer::DeserializeValue(BsonType type, bool promoteLongs) -{ - switch(type) - { - case BSON_TYPE_STRING: - return ReadString(); - - case BSON_TYPE_INT: - return NanNew(ReadInt32()); - - case BSON_TYPE_NUMBER: - return NanNew(ReadDouble()); - - case BSON_TYPE_NULL: - return NanNull(); - - case BSON_TYPE_UNDEFINED: - return NanNull(); - - case BSON_TYPE_TIMESTAMP: - { - int32_t lowBits = ReadInt32(); - int32_t highBits = ReadInt32(); - Local argv[] = { NanNew(lowBits), NanNew(highBits) }; - return NanNew(bson->timestampConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_BOOLEAN: - return (ReadByte() != 0) ? NanTrue() : NanFalse(); - - case BSON_TYPE_REGEXP: - { - const Handle& regex = ReadCString(); - if(regex->IsNull()) ThrowAllocatedStringException(64, "Bad BSON Document: illegal CString"); - int32_t options = ReadRegexOptions(); - return NanNew(regex->ToString(), (RegExp::Flags) options); - } - - case BSON_TYPE_CODE: - { - const Local& code = ReadString(); - const Local& scope = NanNew(); - Local argv[] = { code, scope }; - return NanNew(bson->codeConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_CODE_W_SCOPE: - { - ReadUInt32(); - const Local& code = ReadString(); - const Handle& scope = DeserializeDocument(promoteLongs); - Local argv[] = { code, scope->ToObject() }; - return NanNew(bson->codeConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_OID: - { - Local argv[] = { ReadObjectId() }; - return NanNew(bson->objectIDConstructor)->NewInstance(1, argv); - } - - case BSON_TYPE_BINARY: - { - uint32_t length = ReadUInt32(); - uint32_t subType = ReadByte(); - if(subType == 0x02) { - length = ReadInt32(); - } - - Local buffer = NanNewBufferHandle(p, length); - p += length; - - Handle argv[] = { buffer, NanNew(subType) }; - return NanNew(bson->binaryConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_LONG: - { - // Read 32 bit integers - int32_t lowBits = (int32_t) ReadInt32(); - int32_t highBits = (int32_t) ReadInt32(); - - // Promote long is enabled - if(promoteLongs) { - // If value is < 2^53 and >-2^53 - if((highBits < 0x200000 || (highBits == 0x200000 && lowBits == 0)) && highBits >= -0x200000) { - // Adjust the pointer and read as 64 bit value - p -= 8; - // Read the 64 bit value - int64_t finalValue = (int64_t) ReadInt64(); - return NanNew(finalValue); - } - } - - // Decode the Long value - Local argv[] = { NanNew(lowBits), NanNew(highBits) }; - return NanNew(bson->longConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_DATE: - return NanNew((double) ReadInt64()); - - case BSON_TYPE_ARRAY: - return DeserializeArray(promoteLongs); - - case BSON_TYPE_OBJECT: - return DeserializeDocument(promoteLongs); - - case BSON_TYPE_SYMBOL: - { - const Local& string = ReadString(); - Local argv[] = { string }; - return NanNew(bson->symbolConstructor)->NewInstance(1, argv); - } - - case BSON_TYPE_MIN_KEY: - return NanNew(bson->minKeyConstructor)->NewInstance(); - - case BSON_TYPE_MAX_KEY: - return NanNew(bson->maxKeyConstructor)->NewInstance(); - - default: - ThrowAllocatedStringException(64, "Unhandled BSON Type: %d", type); - } - - return NanNull(); -} - -Persistent BSON::constructor_template; - -BSON::BSON() : ObjectWrap() -{ - // Setup pre-allocated comparision objects - NanAssignPersistent(_bsontypeString, NanNew("_bsontype")); - NanAssignPersistent(_longLowString, NanNew("low_")); - NanAssignPersistent(_longHighString, NanNew("high_")); - NanAssignPersistent(_objectIDidString, NanNew("id")); - NanAssignPersistent(_binaryPositionString, NanNew("position")); - NanAssignPersistent(_binarySubTypeString, NanNew("sub_type")); - NanAssignPersistent(_binaryBufferString, NanNew("buffer")); - NanAssignPersistent(_doubleValueString, NanNew("value")); - NanAssignPersistent(_symbolValueString, NanNew("value")); - NanAssignPersistent(_dbRefRefString, NanNew("$ref")); - NanAssignPersistent(_dbRefIdRefString, NanNew("$id")); - NanAssignPersistent(_dbRefDbRefString, NanNew("$db")); - NanAssignPersistent(_dbRefNamespaceString, NanNew("namespace")); - NanAssignPersistent(_dbRefDbString, NanNew("db")); - NanAssignPersistent(_dbRefOidString, NanNew("oid")); - NanAssignPersistent(_codeCodeString, NanNew("code")); - NanAssignPersistent(_codeScopeString, NanNew("scope")); - NanAssignPersistent(_toBSONString, NanNew("toBSON")); - - NanAssignPersistent(longString, NanNew("Long")); - NanAssignPersistent(objectIDString, NanNew("ObjectID")); - NanAssignPersistent(binaryString, NanNew("Binary")); - NanAssignPersistent(codeString, NanNew("Code")); - NanAssignPersistent(dbrefString, NanNew("DBRef")); - NanAssignPersistent(symbolString, NanNew("Symbol")); - NanAssignPersistent(doubleString, NanNew("Double")); - NanAssignPersistent(timestampString, NanNew("Timestamp")); - NanAssignPersistent(minKeyString, NanNew("MinKey")); - NanAssignPersistent(maxKeyString, NanNew("MaxKey")); -} - -void BSON::Initialize(v8::Handle target) -{ - // Grab the scope of the call from Node - NanScope(); - // Define a new function template - Local t = NanNew(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(NanNew("BSON")); - - // Instance methods - NODE_SET_PROTOTYPE_METHOD(t, "calculateObjectSize", CalculateObjectSize); - NODE_SET_PROTOTYPE_METHOD(t, "serialize", BSONSerialize); - NODE_SET_PROTOTYPE_METHOD(t, "serializeWithBufferAndIndex", SerializeWithBufferAndIndex); - NODE_SET_PROTOTYPE_METHOD(t, "deserialize", BSONDeserialize); - NODE_SET_PROTOTYPE_METHOD(t, "deserializeStream", BSONDeserializeStream); - - NanAssignPersistent(constructor_template, t); - - target->ForceSet(NanNew("BSON"), t->GetFunction()); -} - -// Create a new instance of BSON and passing it the existing context -NAN_METHOD(BSON::New) -{ - NanScope(); - - // Check that we have an array - if(args.Length() == 1 && args[0]->IsArray()) - { - // Cast the array to a local reference - Local array = Local::Cast(args[0]); - - if(array->Length() > 0) - { - // Create a bson object instance and return it - BSON *bson = new BSON(); - - uint32_t foundClassesMask = 0; - - // Iterate over all entries to save the instantiate functions - for(uint32_t i = 0; i < array->Length(); i++) { - // Let's get a reference to the function - Local func = Local::Cast(array->Get(i)); - Local functionName = func->GetName()->ToString(); - - // Save the functions making them persistant handles (they don't get collected) - if(functionName->StrictEquals(NanNew(bson->longString))) { - NanAssignPersistent(bson->longConstructor, func); - foundClassesMask |= 1; - } else if(functionName->StrictEquals(NanNew(bson->objectIDString))) { - NanAssignPersistent(bson->objectIDConstructor, func); - foundClassesMask |= 2; - } else if(functionName->StrictEquals(NanNew(bson->binaryString))) { - NanAssignPersistent(bson->binaryConstructor, func); - foundClassesMask |= 4; - } else if(functionName->StrictEquals(NanNew(bson->codeString))) { - NanAssignPersistent(bson->codeConstructor, func); - foundClassesMask |= 8; - } else if(functionName->StrictEquals(NanNew(bson->dbrefString))) { - NanAssignPersistent(bson->dbrefConstructor, func); - foundClassesMask |= 0x10; - } else if(functionName->StrictEquals(NanNew(bson->symbolString))) { - NanAssignPersistent(bson->symbolConstructor, func); - foundClassesMask |= 0x20; - } else if(functionName->StrictEquals(NanNew(bson->doubleString))) { - NanAssignPersistent(bson->doubleConstructor, func); - foundClassesMask |= 0x40; - } else if(functionName->StrictEquals(NanNew(bson->timestampString))) { - NanAssignPersistent(bson->timestampConstructor, func); - foundClassesMask |= 0x80; - } else if(functionName->StrictEquals(NanNew(bson->minKeyString))) { - NanAssignPersistent(bson->minKeyConstructor, func); - foundClassesMask |= 0x100; - } else if(functionName->StrictEquals(NanNew(bson->maxKeyString))) { - NanAssignPersistent(bson->maxKeyConstructor, func); - foundClassesMask |= 0x200; - } - } - - // Check if we have the right number of constructors otherwise throw an error - if(foundClassesMask != 0x3ff) { - delete bson; - return NanThrowError("Missing function constructor for either [Long/ObjectID/Binary/Code/DbRef/Symbol/Double/Timestamp/MinKey/MaxKey]"); - } else { - bson->Wrap(args.This()); - NanReturnValue(args.This()); - } - } - else - { - return NanThrowError("No types passed in"); - } - } - else - { - return NanThrowTypeError("Argument passed in must be an array of types"); - } -} - -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ - -NAN_METHOD(BSON::BSONDeserialize) -{ - NanScope(); - - // Fail if the first argument is not a string or a buffer - if(args.Length() > 1 && !args[0]->IsString() && !Buffer::HasInstance(args[0])) - return NanThrowError("First Argument must be a Buffer or String."); - - // Promote longs - bool promoteLongs = true; - - // If we have an options object - if(args.Length() == 2 && args[1]->IsObject()) { - Local options = args[1]->ToObject(); - - if(options->Has(NanNew("promoteLongs"))) { - promoteLongs = options->Get(NanNew("promoteLongs"))->ToBoolean()->Value(); - } - } - - // Define pointer to data - Local obj = args[0]->ToObject(); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // If we passed in a buffer, let's unpack it, otherwise let's unpack the string - if(Buffer::HasInstance(obj)) - { -#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Local buffer = ObjectWrap::Unwrap(obj); - char* data = buffer->data(); - size_t length = buffer->length(); -#else - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); -#endif - - // Validate that we have at least 5 bytes - if(length < 5) return NanThrowError("corrupt bson message < 5 bytes long"); - - try - { - BSONDeserializer deserializer(bson, data, length); - // deserializer.promoteLongs = promoteLongs; - NanReturnValue(deserializer.DeserializeDocument(promoteLongs)); - } - catch(char* exception) - { - Local error = NanNew(exception); - free(exception); - return NanThrowError(error); - } - - } - else - { - // The length of the data for this encoding - ssize_t len = DecodeBytes(args[0], BINARY); - - // Validate that we have at least 5 bytes - if(len < 5) return NanThrowError("corrupt bson message < 5 bytes long"); - - // Let's define the buffer size - char* data = (char *)malloc(len); - if(data == NULL) die("Failed to allocate char buffer for BSON serialization"); - DecodeWrite(data, len, args[0], BINARY); - - try - { - BSONDeserializer deserializer(bson, data, len); - // deserializer.promoteLongs = promoteLongs; - Handle result = deserializer.DeserializeDocument(promoteLongs); - free(data); - NanReturnValue(result); - - } - catch(char* exception) - { - Local error = NanNew(exception); - free(exception); - free(data); - return NanThrowError(error); - } - } -} - -Local BSON::GetSerializeObject(const Handle& argValue) -{ - Local object = argValue->ToObject(); - if(object->Has(NanNew(_toBSONString))) - { - const Local& toBSON = object->Get(NanNew(_toBSONString)); - if(!toBSON->IsFunction()) ThrowAllocatedStringException(64, "toBSON is not a function"); - - Local result = Local::Cast(toBSON)->Call(object, 0, NULL); - if(!result->IsObject()) ThrowAllocatedStringException(64, "toBSON function did not return an object"); - return result->ToObject(); - } - else - { - return object; - } -} - -NAN_METHOD(BSON::BSONSerialize) -{ - NanScope(); - - if(args.Length() == 1 && !args[0]->IsObject()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 3 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean() && !args[3]->IsBoolean()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); - if(args.Length() > 4) return NanThrowError("One, two, tree or four arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); - - // Check if we have an array as the object - if(args[0]->IsArray()) return NanThrowError("Only javascript objects supported"); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // Calculate the total size of the document in binary form to ensure we only allocate memory once - // With serialize function - bool serializeFunctions = (args.Length() >= 4) && args[3]->BooleanValue(); - - char *serialized_object = NULL; - size_t object_size; - try - { - Local object = bson->GetSerializeObject(args[0]); - - BSONSerializer counter(bson, false, serializeFunctions); - counter.SerializeDocument(object); - object_size = counter.GetSerializeSize(); - - // Allocate the memory needed for the serialization - serialized_object = (char *)malloc(object_size); - if(serialized_object == NULL) die("Failed to allocate memory for object"); - - // Check if we have a boolean value - bool checkKeys = args.Length() >= 3 && args[1]->IsBoolean() && args[1]->BooleanValue(); - BSONSerializer data(bson, checkKeys, serializeFunctions, serialized_object); - data.SerializeDocument(object); - } - catch(char *err_msg) - { - free(serialized_object); - Local error = NanNew(err_msg); - free(err_msg); - return NanThrowError(error); - } - - // If we have 3 arguments - if(args.Length() == 3 || args.Length() == 4) - { - Local buffer = NanNewBufferHandle(serialized_object, object_size); - free(serialized_object); - NanReturnValue(buffer); - } - else - { - Local bin_value = Encode(serialized_object, object_size, BINARY)->ToString(); - free(serialized_object); - NanReturnValue(bin_value); - } -} - -NAN_METHOD(BSON::CalculateObjectSize) -{ - NanScope(); - // Ensure we have a valid object - if(args.Length() == 1 && !args[0]->IsObject()) return NanThrowError("One argument required - [object]"); - if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return NanThrowError("Two arguments required - [object, boolean]"); - if(args.Length() > 3) return NanThrowError("One or two arguments required - [object] or [object, boolean]"); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - bool serializeFunctions = (args.Length() >= 2) && args[1]->BooleanValue(); - BSONSerializer countSerializer(bson, false, serializeFunctions); - countSerializer.SerializeDocument(args[0]); - - // Return the object size - NanReturnValue(NanNew((uint32_t) countSerializer.GetSerializeSize())); -} - -NAN_METHOD(BSON::SerializeWithBufferAndIndex) -{ - NanScope(); - - //BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, ->, buffer, index) { - // Ensure we have the correct values - if(args.Length() > 5) return NanThrowError("Four or five parameters required [object, boolean, Buffer, int] or [object, boolean, Buffer, int, boolean]"); - if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32()) return NanThrowError("Four parameters required [object, boolean, Buffer, int]"); - if(args.Length() == 5 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32() && !args[4]->IsBoolean()) return NanThrowError("Four parameters required [object, boolean, Buffer, int, boolean]"); - - uint32_t index; - size_t object_size; - - try - { - BSON *bson = ObjectWrap::Unwrap(args.This()); - - Local obj = args[2]->ToObject(); - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); - - index = args[3]->Uint32Value(); - bool checkKeys = args.Length() >= 4 && args[1]->IsBoolean() && args[1]->BooleanValue(); - bool serializeFunctions = (args.Length() == 5) && args[4]->BooleanValue(); - - BSONSerializer dataSerializer(bson, checkKeys, serializeFunctions, data+index); - dataSerializer.SerializeDocument(bson->GetSerializeObject(args[0])); - object_size = dataSerializer.GetSerializeSize(); - - if(object_size + index > length) return NanThrowError("Serious error - overflowed buffer!!"); - } - catch(char *exception) - { - Local error = NanNew(exception); - free(exception); - return NanThrowError(error); - } - - NanReturnValue(NanNew((uint32_t) (index + object_size - 1))); -} - -NAN_METHOD(BSON::BSONDeserializeStream) -{ - NanScope(); - - // At least 3 arguments required - if(args.Length() < 5) return NanThrowError("Arguments required (Buffer(data), Number(index in data), Number(number of documents to deserialize), Array(results), Number(index in the array), Object(optional))"); - - // If the number of argumets equals 3 - if(args.Length() >= 5) - { - if(!Buffer::HasInstance(args[0])) return NanThrowError("First argument must be Buffer instance"); - if(!args[1]->IsUint32()) return NanThrowError("Second argument must be a positive index number"); - if(!args[2]->IsUint32()) return NanThrowError("Third argument must be a positive number of documents to deserialize"); - if(!args[3]->IsArray()) return NanThrowError("Fourth argument must be an array the size of documents to deserialize"); - if(!args[4]->IsUint32()) return NanThrowError("Sixth argument must be a positive index number"); - } - - // If we have 4 arguments - if(args.Length() == 6 && !args[5]->IsObject()) return NanThrowError("Fifth argument must be an object with options"); - - // Define pointer to data - Local obj = args[0]->ToObject(); - uint32_t numberOfDocuments = args[2]->Uint32Value(); - uint32_t index = args[1]->Uint32Value(); - uint32_t resultIndex = args[4]->Uint32Value(); - bool promoteLongs = true; - - // Check for the value promoteLongs in the options object - if(args.Length() == 6) { - Local options = args[5]->ToObject(); - - // Check if we have the promoteLong variable - if(options->Has(NanNew("promoteLongs"))) { - promoteLongs = options->Get(NanNew("promoteLongs"))->ToBoolean()->Value(); - } - } - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // Unpack the buffer variable -#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Local buffer = ObjectWrap::Unwrap(obj); - char* data = buffer->data(); - size_t length = buffer->length(); -#else - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); -#endif - - // Fetch the documents - Local documents = args[3]->ToObject(); - - BSONDeserializer deserializer(bson, data+index, length-index); - for(uint32_t i = 0; i < numberOfDocuments; i++) - { - try - { - documents->Set(i + resultIndex, deserializer.DeserializeDocument(promoteLongs)); - } - catch (char* exception) - { - Local error = NanNew(exception); - free(exception); - return NanThrowError(error); - } - } - - // Return new index of parsing - NanReturnValue(NanNew((uint32_t) (index + deserializer.GetSerializeSize()))); -} - -// Exporting function -extern "C" void init(Handle target) -{ - NanScope(); - BSON::Initialize(target); -} - -NODE_MODULE(bson, BSON::Initialize); diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/bson.h b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/bson.h deleted file mode 100755 index a7feff7d..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/bson.h +++ /dev/null @@ -1,278 +0,0 @@ -//=========================================================================== - -#ifndef BSON_H_ -#define BSON_H_ - -//=========================================================================== - -#ifdef __arm__ -#define USE_MISALIGNED_MEMORY_ACCESS 0 -#else -#define USE_MISALIGNED_MEMORY_ACCESS 1 -#endif - -#include -#include -#include -#include "nan.h" - -using namespace v8; -using namespace node; - -//=========================================================================== - -enum BsonType -{ - BSON_TYPE_NUMBER = 1, - BSON_TYPE_STRING = 2, - BSON_TYPE_OBJECT = 3, - BSON_TYPE_ARRAY = 4, - BSON_TYPE_BINARY = 5, - BSON_TYPE_UNDEFINED = 6, - BSON_TYPE_OID = 7, - BSON_TYPE_BOOLEAN = 8, - BSON_TYPE_DATE = 9, - BSON_TYPE_NULL = 10, - BSON_TYPE_REGEXP = 11, - BSON_TYPE_CODE = 13, - BSON_TYPE_SYMBOL = 14, - BSON_TYPE_CODE_W_SCOPE = 15, - BSON_TYPE_INT = 16, - BSON_TYPE_TIMESTAMP = 17, - BSON_TYPE_LONG = 18, - BSON_TYPE_MAX_KEY = 0x7f, - BSON_TYPE_MIN_KEY = 0xff -}; - -//=========================================================================== - -template class BSONSerializer; - -class BSON : public ObjectWrap { -public: - BSON(); - ~BSON() {} - - static void Initialize(Handle target); - static NAN_METHOD(BSONDeserializeStream); - - // JS based objects - static NAN_METHOD(BSONSerialize); - static NAN_METHOD(BSONDeserialize); - - // Calculate size of function - static NAN_METHOD(CalculateObjectSize); - static NAN_METHOD(SerializeWithBufferAndIndex); - - // Constructor used for creating new BSON objects from C++ - static Persistent constructor_template; - -private: - static NAN_METHOD(New); - static Handle deserialize(BSON *bson, char *data, uint32_t dataLength, uint32_t startIndex, bool is_array_item); - - // BSON type instantiate functions - Persistent longConstructor; - Persistent objectIDConstructor; - Persistent binaryConstructor; - Persistent codeConstructor; - Persistent dbrefConstructor; - Persistent symbolConstructor; - Persistent doubleConstructor; - Persistent timestampConstructor; - Persistent minKeyConstructor; - Persistent maxKeyConstructor; - - // Equality Objects - Persistent longString; - Persistent objectIDString; - Persistent binaryString; - Persistent codeString; - Persistent dbrefString; - Persistent symbolString; - Persistent doubleString; - Persistent timestampString; - Persistent minKeyString; - Persistent maxKeyString; - - // Equality speed up comparison objects - Persistent _bsontypeString; - Persistent _longLowString; - Persistent _longHighString; - Persistent _objectIDidString; - Persistent _binaryPositionString; - Persistent _binarySubTypeString; - Persistent _binaryBufferString; - Persistent _doubleValueString; - Persistent _symbolValueString; - - Persistent _dbRefRefString; - Persistent _dbRefIdRefString; - Persistent _dbRefDbRefString; - Persistent _dbRefNamespaceString; - Persistent _dbRefDbString; - Persistent _dbRefOidString; - - Persistent _codeCodeString; - Persistent _codeScopeString; - Persistent _toBSONString; - - Local GetSerializeObject(const Handle& object); - - template friend class BSONSerializer; - friend class BSONDeserializer; -}; - -//=========================================================================== - -class CountStream -{ -public: - CountStream() : count(0) { } - - void WriteByte(int value) { ++count; } - void WriteByte(const Handle&, const Handle&) { ++count; } - void WriteBool(const Handle& value) { ++count; } - void WriteInt32(int32_t value) { count += 4; } - void WriteInt32(const Handle& value) { count += 4; } - void WriteInt32(const Handle& object, const Handle& key) { count += 4; } - void WriteInt64(int64_t value) { count += 8; } - void WriteInt64(const Handle& value) { count += 8; } - void WriteDouble(double value) { count += 8; } - void WriteDouble(const Handle& value) { count += 8; } - void WriteDouble(const Handle&, const Handle&) { count += 8; } - void WriteUInt32String(uint32_t name) { char buffer[32]; count += sprintf(buffer, "%u", name) + 1; } - void WriteLengthPrefixedString(const Local& value) { count += value->Utf8Length()+5; } - void WriteObjectId(const Handle& object, const Handle& key) { count += 12; } - void WriteString(const Local& value) { count += value->Utf8Length() + 1; } // This returns the number of bytes exclusive of the NULL terminator - void WriteData(const char* data, size_t length) { count += length; } - - void* BeginWriteType() { ++count; return NULL; } - void CommitType(void*, BsonType) { } - void* BeginWriteSize() { count += 4; return NULL; } - void CommitSize(void*) { } - - size_t GetSerializeSize() const { return count; } - - // Do nothing. CheckKey is implemented for DataStream - void CheckKey(const Local&) { } - -private: - size_t count; -}; - -class DataStream -{ -public: - DataStream(char* aDestinationBuffer) : destinationBuffer(aDestinationBuffer), p(aDestinationBuffer) { } - - void WriteByte(int value) { *p++ = value; } - void WriteByte(const Handle& object, const Handle& key) { *p++ = object->Get(key)->Int32Value(); } -#if USE_MISALIGNED_MEMORY_ACCESS - void WriteInt32(int32_t value) { *reinterpret_cast(p) = value; p += 4; } - void WriteInt64(int64_t value) { *reinterpret_cast(p) = value; p += 8; } - void WriteDouble(double value) { *reinterpret_cast(p) = value; p += 8; } -#else - void WriteInt32(int32_t value) { memcpy(p, &value, 4); p += 4; } - void WriteInt64(int64_t value) { memcpy(p, &value, 8); p += 8; } - void WriteDouble(double value) { memcpy(p, &value, 8); p += 8; } -#endif - void WriteBool(const Handle& value) { WriteByte(value->BooleanValue() ? 1 : 0); } - void WriteInt32(const Handle& value) { WriteInt32(value->Int32Value()); } - void WriteInt32(const Handle& object, const Handle& key) { WriteInt32(object->Get(key)); } - void WriteInt64(const Handle& value) { WriteInt64(value->IntegerValue()); } - void WriteDouble(const Handle& value) { WriteDouble(value->NumberValue()); } - void WriteDouble(const Handle& object, const Handle& key) { WriteDouble(object->Get(key)); } - void WriteUInt32String(uint32_t name) { p += sprintf(p, "%u", name) + 1; } - void WriteLengthPrefixedString(const Local& value) { WriteInt32(value->Utf8Length()+1); WriteString(value); } - void WriteObjectId(const Handle& object, const Handle& key); - void WriteString(const Local& value) { p += value->WriteUtf8(p); } // This returns the number of bytes inclusive of the NULL terminator. - void WriteData(const char* data, size_t length) { memcpy(p, data, length); p += length; } - - void* BeginWriteType() { void* returnValue = p; p++; return returnValue; } - void CommitType(void* beginPoint, BsonType value) { *reinterpret_cast(beginPoint) = value; } - void* BeginWriteSize() { void* returnValue = p; p += 4; return returnValue; } - -#if USE_MISALIGNED_MEMORY_ACCESS - void CommitSize(void* beginPoint) { *reinterpret_cast(beginPoint) = (int32_t) (p - (char*) beginPoint); } -#else - void CommitSize(void* beginPoint) { int32_t value = (int32_t) (p - (char*) beginPoint); memcpy(beginPoint, &value, 4); } -#endif - - size_t GetSerializeSize() const { return p - destinationBuffer; } - - void CheckKey(const Local& keyName); - -protected: - char *const destinationBuffer; // base, never changes - char* p; // cursor into buffer -}; - -template class BSONSerializer : public T -{ -private: - typedef T Inherited; - -public: - BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions) : Inherited(), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { } - BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions, char* parentParam) : Inherited(parentParam), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { } - - void SerializeDocument(const Handle& value); - void SerializeArray(const Handle& value); - void SerializeValue(void* typeLocation, const Handle value); - -private: - bool checkKeys; - bool serializeFunctions; - BSON* bson; -}; - -//=========================================================================== - -class BSONDeserializer -{ -public: - BSONDeserializer(BSON* aBson, char* data, size_t length); - BSONDeserializer(BSONDeserializer& parentSerializer, size_t length); - - Handle DeserializeDocument(bool promoteLongs); - - bool HasMoreData() const { return p < pEnd; } - Handle ReadCString(); - uint32_t ReadIntegerString(); - int32_t ReadRegexOptions(); - Local ReadString(); - Local ReadObjectId(); - - unsigned char ReadByte() { return *reinterpret_cast(p++); } -#if USE_MISALIGNED_MEMORY_ACCESS - int32_t ReadInt32() { int32_t returnValue = *reinterpret_cast(p); p += 4; return returnValue; } - uint32_t ReadUInt32() { uint32_t returnValue = *reinterpret_cast(p); p += 4; return returnValue; } - int64_t ReadInt64() { int64_t returnValue = *reinterpret_cast(p); p += 8; return returnValue; } - double ReadDouble() { double returnValue = *reinterpret_cast(p); p += 8; return returnValue; } -#else - int32_t ReadInt32() { int32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; } - uint32_t ReadUInt32() { uint32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; } - int64_t ReadInt64() { int64_t returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; } - double ReadDouble() { double returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; } -#endif - - size_t GetSerializeSize() const { return p - pStart; } - -private: - Handle DeserializeArray(bool promoteLongs); - Handle DeserializeValue(BsonType type, bool promoteLongs); - Handle DeserializeDocumentInternal(bool promoteLongs); - Handle DeserializeArrayInternal(bool promoteLongs); - - BSON* bson; - char* const pStart; - char* p; - char* const pEnd; -}; - -//=========================================================================== - -#endif // BSON_H_ - -//=========================================================================== diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/index.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/index.js deleted file mode 100755 index 0d3cd35a..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/index.js +++ /dev/null @@ -1,41 +0,0 @@ -var bson = null; - -try { - // Load the precompiled win32 binary - if(process.platform == "win32" && process.arch == "x64") { - bson = require('./win32/x64/bson'); - } else if(process.platform == "win32" && process.arch == "ia32") { - bson = require('./win32/ia32/bson'); - } else { - bson = require('../build/Release/bson'); - } -} catch(err) { - // Attempt to load the release bson version - try { - bson = require('../build/Release/bson'); - } catch (err) { - console.dir(err) - console.error("js-bson: Failed to load c++ bson extension, using pure JS version"); - bson = require('../lib/bson/bson'); - } -} - -exports.BSON = bson.BSON; -exports.Long = require('../lib/bson/long').Long; -exports.ObjectID = require('../lib/bson/objectid').ObjectID; -exports.DBRef = require('../lib/bson/db_ref').DBRef; -exports.Code = require('../lib/bson/code').Code; -exports.Timestamp = require('../lib/bson/timestamp').Timestamp; -exports.Binary = require('../lib/bson/binary').Binary; -exports.Double = require('../lib/bson/double').Double; -exports.MaxKey = require('../lib/bson/max_key').MaxKey; -exports.MinKey = require('../lib/bson/min_key').MinKey; -exports.Symbol = require('../lib/bson/symbol').Symbol; - -// Just add constants tot he Native BSON parser -exports.BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -exports.BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -exports.BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -exports.BSON.BSON_BINARY_SUBTYPE_UUID = 3; -exports.BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -exports.BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node deleted file mode 100755 index 7f54835e..00000000 Binary files a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node and /dev/null differ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node deleted file mode 100755 index f01f8be3..00000000 Binary files a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node and /dev/null differ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/wscript b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/wscript deleted file mode 100755 index 40f5317f..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/ext/wscript +++ /dev/null @@ -1,39 +0,0 @@ -import Options -from os import unlink, symlink, popen -from os.path import exists - -srcdir = "." -blddir = "build" -VERSION = "0.1.0" - -def set_options(opt): - opt.tool_options("compiler_cxx") - opt.add_option( '--debug' - , action='store_true' - , default=False - , help='Build debug variant [Default: False]' - , dest='debug' - ) - -def configure(conf): - conf.check_tool("compiler_cxx") - conf.check_tool("node_addon") - conf.env.append_value('CXXFLAGS', ['-O3', '-funroll-loops']) - - # conf.env.append_value('CXXFLAGS', ['-DDEBUG', '-g', '-O0', '-Wall', '-Wextra']) - # conf.check(lib='node', libpath=['/usr/lib', '/usr/local/lib'], uselib_store='NODE') - -def build(bld): - obj = bld.new_task_gen("cxx", "shlib", "node_addon") - obj.target = "bson" - obj.source = ["bson.cc"] - # obj.uselib = "NODE" - -def shutdown(): - # HACK to get compress.node out of build directory. - # better way to do this? - if Options.commands['clean']: - if exists('bson.node'): unlink('bson.node') - else: - if exists('build/default/bson.node') and not exists('bson.node'): - symlink('build/default/bson.node', 'bson.node') diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/binary.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/binary.js deleted file mode 100755 index 5d0acfa4..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,344 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, 'binary', offset); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if(asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) - return this.buffer; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @method - * @return {number} the length of the binary. - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -/** - * Binary default subtype - * @ignore - */ -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -module.exports = Binary; -module.exports.Binary = Binary; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js deleted file mode 100755 index d2fc811f..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js +++ /dev/null @@ -1,385 +0,0 @@ -/** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/bson.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/bson.js deleted file mode 100755 index fc576008..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,1573 +0,0 @@ -var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - // If we have toBSON defined, override the current object - if(value && value.toBSON){ - value = value.toBSON(); - } - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - if(object.toBSON) { - if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); - object = object.toBSON(); - if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); - } - - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - - // If we have toBSON defined, override the current object - if(value && value.toBSON){ - value = value.toBSON(); - } - - var startIndex = index; - - switch(typeof value) { - case 'string': - // console.log("+++++++++++ index string:: " + index) - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // console.log("====== key :: " + name + " size ::" + size) - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // console.log("+++++++++++ index OBJECTID:: " + index) - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long || value['_bsontype'] == 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - // console.log("++++++++++++++++++++++++++++++++++++ OLDJS :: " + buffer.length) - // console.log(buffer.toString('hex')) - // console.log(buffer.toString('ascii')) - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_UNDEFINED: - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/bson_new.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/bson_new.js deleted file mode 100755 index 0b1b38d9..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/bson_new.js +++ /dev/null @@ -1,776 +0,0 @@ -var writeIEEE754 = require('./float_parser').writeIEEE754 - , Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser; - -// Max Document Buffer size -var buffer = new Buffer(1024 * 1024 * 16); - -var checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -var serializeString = function(key, value, index) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = Buffer.byteLength(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - buffer.write(value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; -} - -var serializeNumber = function(key, value, index) { - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; -} - -var serializeUndefined = function(key, value, index) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} - -var serializeBoolean = function(key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -} - -var serializeDate = function(key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} - -var serializeRegExp = function(key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + Buffer.byteLength(value.source); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; -} - -var serializeMinMax = function(key, value, index) { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} - -var serializeObjectId = function(key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - for(var j = 0; j < 12; j++) { - buffer[index + j] = value.binId[j]; - } - - // Ajust index - index = index + 12; - return index; -} - -var serializeBuffer = function(key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; -} - -var serializeObject = function(key, value, index, checkKeys, depth) { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(value, checkKeys, index, depth + 1); - // Write size - var size = endIndex - index; - return endIndex; -} - -var serializeLong = function(key, value, index) { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} - -var serializeDouble = function(key, value, index) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; -} - -var serializeCode = function(key, value, index, checkKeys, depth) { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code == 'string' ? value.code : value.code.toString(); - var codeSize = Buffer.byteLength(functionString) + 1; - // Index adjustment - index = index + 4; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write string into buffer - buffer.write(functionString, index + 4, 'utf8'); - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto(value.scope, checkKeys, index, depth + 1) - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = Buffer.byteLength(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(functionString, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; -} - -var serializeBinary = function(key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; -} - -var serializeSymbol = function(key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Calculate size - var size = Buffer.byteLength(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -} - -var serializeDBRef = function(key, value, index, depth) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if(null != value.db) { - endIndex = serializeInto({ - '$ref': value.namespace - , '$id' : value.oid - , '$db' : value.db - }, false, index, depth + 1); - } else { - endIndex = serializeInto({ - '$ref': value.namespace - , '$id' : value.oid - }, false, index, depth + 1); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; -} - -var BSON = function() { - this.buffer = buffer; -} - -BSON.prototype.serialize = function serialize(object, checkKeys, index) { - var finishedBuffer = new Buffer(serializeInto(object, checkKeys, index || 0, 0)); - this.buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - return finishedBuffer; -} - -var serializeInto = function serializeInto(object, checkKeys, startingIndex, depth) { - startingIndex = startingIndex || 0; - - // Start place to serialize into - var index = startingIndex + 4; - var self = this; - - // Special case isArray - if(Array.isArray(object)) { - // Get object keys - for(var i = 0; i < object.length; i++) { - var key = "" + i; - var type = typeof object[i]; - - // Check the key and throw error if it's illegal - if(key != '$db' && key != '$ref' && key != '$id') { - checkKey(key, !checkKeys); - } - - if(type == 'string') { - index = serializeString(key, object[i], index); - } else if(type == 'number') { - index = serializeNumber(key, object[i], index); - } else if(type == 'undefined') { - index = serializeUndefined(key, object[i], index); - } else if(type == 'boolean') { - index = serializeBoolean(key, object[i], index); - } else if(object[i] instanceof Date) { - index = serializeDate(key, object[i], index); - } else if(object[i] instanceof RegExp || Object.prototype.toString.call(object[i]) === '[object RegExp]') { - index = serializeRegExp(key, object[i], index); - } else if(object[i]['_bsontype'] == 'MinKey' || object[i]['_bsontype'] == 'MaxKey') { - index = serializeMinMax(key, object[i], index); - } else if(object[i]['_bsontype'] == 'ObjectID') { - index = serializeObjectId(key, object[i], index); - } else if(Buffer.isBuffer(object[i])) { - index = serializeBuffer(key, object[i], index); - } else if(type == 'object' && object[i]['_bsontype'] == null) { - index = serializeObject(key, object[i], index, checkKeys, depth); - } else if(object[i]['_bsontype'] == 'Long' || object[i]['_bsontype'] == 'Timestamp') { - index = serializeLong(key, object[i], index); - } else if(object[i]['_bsontype'] == 'Double') { - index = serializeDouble(key, object[i], index); - } else if(object[i]['_bsontype'] == 'Code') { - index = serializeCode(key, object[i], index, checkKeys, depth); - } else if(object[i]['_bsontype'] == 'Binary') { - index = serializeBinary(key, object[i], index); - } else if(object[i]['_bsontype'] == 'Symbol') { - index = serializeSymbol(key, object[i], index); - } else if(object[i]['_bsontype'] == 'DBRef') { - index = serializeDBRef(key, object[i], index, depth); - } - } - } else { - var keys = Object.keys(object); - for(var i = 0; i < keys.length; i++) { - var key = keys[i]; - var type = typeof object[key]; - - // Check the key and throw error if it's illegal - if(key != '$db' && key != '$ref' && key != '$id') { - checkKey(key, !checkKeys); - } - - if(type == 'string') { - index = serializeString(key, object[key], index); - } else if(type == 'number') { - index = serializeNumber(key, object[key], index); - } else if(type == 'undefined') { - index = serializeUndefined(key, object[key], index); - } else if(type == 'boolean') { - index = serializeBoolean(key, object[key], index); - } else if(object[key] instanceof Date) { - index = serializeDate(key, object[key], index); - } else if(object[key] instanceof RegExp || Object.prototype.toString.call(object[key]) === '[object RegExp]') { - index = serializeRegExp(key, object[key], index); - } else if(object[key]['_bsontype'] == 'MinKey' || object[key]['_bsontype'] == 'MaxKey') { - index = serializeMinMax(key, object[key], index); - } else if(object[key]['_bsontype'] == 'ObjectID') { - index = serializeObjectId(key, object[key], index); - } else if(Buffer.isBuffer(object[key])) { - index = serializeBuffer(key, object[key], index); - } else if(type == 'object' && object[key]['_bsontype'] == null) { - index = serializeObject(key, object[key], index, checkKeys, depth); - } else if(object[key]['_bsontype'] == 'Long' || object[key]['_bsontype'] == 'Timestamp') { - index = serializeLong(key, object[key], index); - } else if(object[key]['_bsontype'] == 'Double') { - index = serializeDouble(key, object[key], index); - } else if(object[key]['_bsontype'] == 'Code') { - index = serializeCode(key, object[key], index, checkKeys, depth); - } else if(object[key]['_bsontype'] == 'Binary') { - index = serializeBinary(key, object[key], index); - } else if(object[key]['_bsontype'] == 'Symbol') { - index = serializeSymbol(key, object[key], index); - } else if(object[key]['_bsontype'] == 'DBRef') { - index = serializeDBRef(key, object[key], index, depth); - } - } - } - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -} - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// Return BSON -exports.BSON = BSON; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/code.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/code.js deleted file mode 100755 index 83a42c96..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -var Code = function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -module.exports = Code; -module.exports.Code = Code; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js deleted file mode 100755 index 06789a6c..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -module.exports = DBRef; -module.exports.DBRef = DBRef; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/double.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/double.js deleted file mode 100755 index 09ed2229..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Double.prototype.toJSON = function() { - return this.value; -} - -module.exports = Double; -module.exports.Double = Double; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js deleted file mode 100755 index 6fca3924..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/index.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/index.js deleted file mode 100755 index 950fcad3..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/index.js +++ /dev/null @@ -1,74 +0,0 @@ -try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('../../ext'); -} catch(err) { - // do nothing -} - -[ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '../../ext' -].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/long.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/long.js deleted file mode 100755 index 6f188850..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,856 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @ignore - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Long; -module.exports.Long = Long; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js deleted file mode 100755 index 03ee9cdd..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -module.exports = MaxKey; -module.exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js deleted file mode 100755 index 5e120fbe..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -module.exports = MinKey; -module.exports.MinKey = MinKey; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js deleted file mode 100755 index 1d4894a0..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,274 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class -* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @property {number} generationTime The generation time of this ObjectId instance -* @return {ObjectID} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id) { - if(!(this instanceof ObjectID)) return new ObjectID(id); - if((id instanceof ObjectID)) return id; - - this._bsontype = 'ObjectID'; - var __id = null; - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if(!valid && id != null){ - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - } else if(valid && typeof id == 'string' && id.length == 24) { - return ObjectID.createFromHexString(id); - } else if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId as well as ObjectID -var ObjectId = ObjectID; - -// Precomputed hex table enables speedy hex string conversion -var hexTable = []; -for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); -} - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @method -* @return {string} return the 24 byte hex string representation. -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @method -* @param {number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {string} return the 12 byte id binary string. -*/ -ObjectID.prototype.generate = function(time) { - if ('number' != typeof time) { - time = parseInt(Date.now()/1000,10); - } - - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid % 0xFFFF); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @method -* @param {object} otherID ObjectID instance to compare against. -* @return {boolean} the result of comparing two ObjectID's -*/ -ObjectID.prototype.equals = function equals (otherID) { - if(otherID == null) return false; - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @method -* @return {date} the generation date -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -*/ -ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); - -/** -* @ignore -*/ -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @method -* @param {number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @method -* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* Checks if a value is a valid bson ObjectId -* -* @method -* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. -*/ -ObjectID.isValid = function isValid(id) { - if(id == null) return false; - - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) { - return false; - } else { - // Check specifically for hex correctness - if(typeof id == 'string' && id.length == 24) return checkForHexRegExp.test(id); - return true; - } -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -module.exports = ObjectID; -module.exports.ObjectID = ObjectID; -module.exports.ObjectId = ObjectID; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js deleted file mode 100755 index 7681a4de..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -module.exports = Symbol; -module.exports.Symbol = Symbol; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js deleted file mode 100755 index 7718cafc..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,856 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @ignore - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Timestamp; -module.exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/.dntrc b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/.dntrc deleted file mode 100755 index 47971da6..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/.dntrc +++ /dev/null @@ -1,30 +0,0 @@ -## DNT config file -## see https://github.com/rvagg/dnt - -NODE_VERSIONS="\ - master \ - v0.11.13 \ - v0.10.30 \ - v0.10.29 \ - v0.10.28 \ - v0.10.26 \ - v0.10.25 \ - v0.10.24 \ - v0.10.23 \ - v0.10.22 \ - v0.10.21 \ - v0.10.20 \ - v0.10.19 \ - v0.8.28 \ - v0.8.27 \ - v0.8.26 \ - v0.8.24 \ -" -OUTPUT_PREFIX="nan-" -TEST_CMD=" \ - cd /dnt/ && \ - npm install && \ - node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \ - node_modules/.bin/tap --gc test/js/*-test.js \ -" - diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/CHANGELOG.md b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/CHANGELOG.md deleted file mode 100755 index 26e859de..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/CHANGELOG.md +++ /dev/null @@ -1,270 +0,0 @@ -# NAN ChangeLog - -**Version 1.7.0: current Node 12: 0.12.0, Node 10: 0.10.36, io.js: 1.4.1** - -### 1.7.0 Feb 28 2015 - - - Feature: Made NanCallback::Call accept optional target 8d54da7 - - Feature: Support atom-shell 0.21 0b7f1bb - -### 1.6.2 Feb 6 2015 - - - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 - -### 1.6.1 Jan 23 2015 - - - Build: version bump - -### 1.5.3 Jan 23 2015 - - - Build: repackage - -### 1.6.0 Jan 23 2015 - - - Deprecated `NanNewContextHandle` in favor of `NanNew` 49259af - - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 - - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 - -### 1.5.2 Jan 23 2015 - - - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 - - Bugfix: Readded missing String constructors 18d828f - - Bugfix: Add overload handling NanNew(..) 5ef813b - - Bugfix: Fix uv_work_cb versioning 997e4ae - - Bugfix: Add function factory and test 4eca89c - - Bugfix: Add object template factory and test cdcb951 - - Correctness: Lifted an io.js related typedef c9490be - - Correctness: Make explicit downcasts of String lengths 00074e6 - - Windows: Limit the scope of disabled warning C4530 83d7deb - -### 1.5.1 Jan 15 2015 - - - Build: version bump - -### 1.4.3 Jan 15 2015 - - - Build: version bump - -### 1.4.2 Jan 15 2015 - - - Feature: Support io.js 0dbc5e8 - -### 1.5.0 Jan 14 2015 - - - Feature: Support io.js b003843 - - Correctness: Improved NanNew internals 9cd4f6a - - Feature: Implement progress to NanAsyncWorker 8d6a160 - -### 1.4.1 Nov 8 2014 - - - Bugfix: Handle DEBUG definition correctly - - Bugfix: Accept int as Boolean - -### 1.4.0 Nov 1 2014 - - - Feature: Added NAN_GC_CALLBACK 6a5c245 - - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 - - Correctness: Added constness to references in NanHasInstance 02c61cd - - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 - - Windoze: Shut Visual Studio up when compiling 8d558c1 - - License: Switch to plain MIT from custom hacked MIT license 11de983 - - Build: Added test target to Makefile e232e46 - - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 - - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 - - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 - -### 1.3.0 Aug 2 2014 - - - Added NanNew(std::string) - - Added NanNew(std::string&) - - Added NanAsciiString helper class - - Added NanUtf8String helper class - - Added NanUcs2String helper class - - Deprecated NanRawString() - - Deprecated NanCString() - - Added NanGetIsolateData(v8::Isolate *isolate) - - Added NanMakeCallback(v8::Handle target, v8::Handle func, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, v8::Handle symbol, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, const char* method, int argc, v8::Handle* argv) - - Added NanSetTemplate(v8::Handle templ, v8::Handle name , v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetPrototypeTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetInstanceTemplate(v8::Local templ, const char *name, v8::Handle value) - - Added NanSetInstanceTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - -### 1.2.0 Jun 5 2014 - - - Add NanSetPrototypeTemplate - - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, - introduced _NanWeakCallbackDispatcher - - Removed -Wno-unused-local-typedefs from test builds - - Made test builds Windows compatible ('Sleep()') - -### 1.1.2 May 28 2014 - - - Release to fix more stuff-ups in 1.1.1 - -### 1.1.1 May 28 2014 - - - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 - -### 1.1.0 May 25 2014 - - - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead - - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), - (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, - v8::String::ExternalAsciiStringResource* - - Deprecate NanSymbol() - - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker - -### 1.0.0 May 4 2014 - - - Heavy API changes for V8 3.25 / Node 0.11.13 - - Use cpplint.py - - Removed NanInitPersistent - - Removed NanPersistentToLocal - - Removed NanFromV8String - - Removed NanMakeWeak - - Removed NanNewLocal - - Removed NAN_WEAK_CALLBACK_OBJECT - - Removed NAN_WEAK_CALLBACK_DATA - - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions - - Introduce NanUndefined, NanNull, NanTrue and NanFalse - - Introduce NanEscapableScope and NanEscapeScope - - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) - - Introduce NanMakeCallback for node::MakeCallback - - Introduce NanSetTemplate - - Introduce NanGetCurrentContext - - Introduce NanCompileScript and NanRunScript - - Introduce NanAdjustExternalMemory - - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback - - Introduce NanGetHeapStatistics - - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() - -### 0.8.0 Jan 9 2014 - - - NanDispose -> NanDisposePersistent, deprecate NanDispose - - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() - -### 0.7.1 Jan 9 2014 - - - Fixes to work against debug builds of Node - - Safer NanPersistentToLocal (avoid reinterpret_cast) - - Speed up common NanRawString case by only extracting flattened string when necessary - -### 0.7.0 Dec 17 2013 - - - New no-arg form of NanCallback() constructor. - - NanCallback#Call takes Handle rather than Local - - Removed deprecated NanCallback#Run method, use NanCallback#Call instead - - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS - - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() - - Introduce NanRawString() for char* (or appropriate void*) from v8::String - (replacement for NanFromV8String) - - Introduce NanCString() for null-terminated char* from v8::String - -### 0.6.0 Nov 21 2013 - - - Introduce NanNewLocal(v8::Handle value) for use in place of - v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 - -### 0.5.2 Nov 16 2013 - - - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public - -### 0.5.1 Nov 12 2013 - - - Use node::MakeCallback() instead of direct v8::Function::Call() - -### 0.5.0 Nov 11 2013 - - - Added @TooTallNate as collaborator - - New, much simpler, "include_dirs" for binding.gyp - - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros - -### 0.4.4 Nov 2 2013 - - - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ - -### 0.4.3 Nov 2 2013 - - - Include node_object_wrap.h, removed from node.h for Node 0.11.8. - -### 0.4.2 Nov 2 2013 - - - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for - Node 0.11.8 release. - -### 0.4.1 Sep 16 2013 - - - Added explicit `#include ` as it was removed from node.h for v0.11.8 - -### 0.4.0 Sep 2 2013 - - - Added NAN_INLINE and NAN_DEPRECATED and made use of them - - Added NanError, NanTypeError and NanRangeError - - Cleaned up code - -### 0.3.2 Aug 30 2013 - - - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent - in NanAsyncWorker - -### 0.3.1 Aug 20 2013 - - - fix "not all control paths return a value" compile warning on some platforms - -### 0.3.0 Aug 19 2013 - - - Made NAN work with NPM - - Lots of fixes to NanFromV8String, pulling in features from new Node core - - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API - - Added optional error number argument for NanThrowError() - - Added NanInitPersistent() - - Added NanReturnNull() and NanReturnEmptyString() - - Added NanLocker and NanUnlocker - - Added missing scopes - - Made sure to clear disposed Persistent handles - - Changed NanAsyncWorker to allocate error messages on the heap - - Changed NanThrowError(Local) to NanThrowError(Handle) - - Fixed leak in NanAsyncWorker when errmsg is used - -### 0.2.2 Aug 5 2013 - - - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() - -### 0.2.1 Aug 5 2013 - - - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for - NanFromV8String() - -### 0.2.0 Aug 5 2013 - - - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, - NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY - - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, - _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, - _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, - _NAN_PROPERTY_QUERY_ARGS - - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer - - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, - NAN_WEAK_CALLBACK_DATA, NanMakeWeak - - Renamed THROW_ERROR to _NAN_THROW_ERROR - - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) - - Added NanBufferUse(char*, uint32_t) - - Added NanNewContextHandle(v8::ExtensionConfiguration*, - v8::Handle, v8::Handle) - - Fixed broken NanCallback#GetFunction() - - Added optional encoding and size arguments to NanFromV8String() - - Added NanGetPointerSafe() and NanSetPointerSafe() - - Added initial test suite (to be expanded) - - Allow NanUInt32OptionValue to convert any Number object - -### 0.1.0 Jul 21 2013 - - - Added `NAN_GETTER`, `NAN_SETTER` - - Added `NanThrowError` with single Local argument - - Added `NanNewBufferHandle` with single uint32_t argument - - Added `NanHasInstance(Persistent&, Handle)` - - Added `Local NanCallback#GetFunction()` - - Added `NanCallback#Call(int, Local[])` - - Deprecated `NanCallback#Run(int, Local[])` in favour of Call diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/LICENSE.md b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/LICENSE.md deleted file mode 100755 index 95c2eb5f..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -The MIT License (MIT) -===================== - -Copyright (c) 2015 NAN contributors ------------------------------------ - -*NAN contributors listed at * - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/appveyor.yml b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/appveyor.yml deleted file mode 100755 index 34294539..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/appveyor.yml +++ /dev/null @@ -1,38 +0,0 @@ -# http://www.appveyor.com/docs/appveyor-yml - -# Test against these versions of Io.js and Node.js. -environment: - matrix: - # node.js - - nodejs_version: "0.8" - - nodejs_version: "0.10" - - nodejs_version: "0.12" - # io.js - - nodejs_version: "1" - -# Install scripts. (runs after repo cloning) -install: - # Get the latest stable version of Node 0.STABLE.latest - - ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version} - - ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)} - - IF NOT %nodejs_version% == 1 npm -g install npm - - IF NOT %nodejs_version% == 1 set PATH=%APPDATA%\npm;%PATH% - # Typical npm stuff. - - npm install - - IF %nodejs_version% == 0.8 node node_modules\node-gyp\bin\node-gyp.js rebuild --directory test - - IF NOT %nodejs_version% == 0.8 npm run rebuild-tests - -# Post-install test scripts. -test_script: - # Output useful info for debugging. - - node --version - - npm --version - # run tests - - IF NOT %nodejs_version% == 1 npm test - - IF %nodejs_version% == 1 iojs node_modules\tap\bin\tap.js --gc test\js\*-test.js - -# Don't actually build. -build: off - -# Set build version format here instead of in the admin panel. -version: "{build}" diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/include_dirs.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/include_dirs.js deleted file mode 100755 index 4f1dfb41..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/include_dirs.js +++ /dev/null @@ -1 +0,0 @@ -console.log(require('path').relative('.', __dirname)); diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan.h b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan.h deleted file mode 100755 index 23c38e43..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan.h +++ /dev/null @@ -1,2212 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2015 NAN contributors: - * - Rod Vagg - * - Benjamin Byholm - * - Trevor Norris - * - Nathan Rajlich - * - Brett Lawson - * - Ben Noordhuis - * - David Siegel - * - * MIT License - * - * Version 1.7.0: current Node 12: 0.12.0, Node 10: 0.10.36, io.js: 1.4.1 - * - * See https://github.com/rvagg/nan for the latest update to this file - **********************************************************************************/ - -#ifndef NAN_H_ -#define NAN_H_ - -#include -#include -#include -#include -#include -#include -#include -#if defined(_MSC_VER) -# pragma warning( disable : 4530 ) -# include -# pragma warning( default : 4530 ) -#else -# include -#endif - -#if defined(__GNUC__) && !(defined(DEBUG) && DEBUG) -# define NAN_INLINE inline __attribute__((always_inline)) -#elif defined(_MSC_VER) && !(defined(DEBUG) && DEBUG) -# define NAN_INLINE __forceinline -#else -# define NAN_INLINE inline -#endif - -#if defined(__GNUC__) && \ - !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) -# define NAN_DEPRECATED __attribute__((deprecated)) -#elif defined(_MSC_VER) && \ - !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) -# define NAN_DEPRECATED __declspec(deprecated) -#else -# define NAN_DEPRECATED -#endif - -#define NODE_0_10_MODULE_VERSION 11 -#define NODE_0_12_MODULE_VERSION 12 -#define ATOM_0_21_MODULE_VERSION 41 -#define IOJS_1_0_MODULE_VERSION 42 -#define IOJS_1_1_MODULE_VERSION 43 - -#if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION) -typedef v8::InvocationCallback NanFunctionCallback; -typedef v8::Script NanUnboundScript; -typedef v8::Script NanBoundScript; -#else -typedef v8::FunctionCallback NanFunctionCallback; -typedef v8::UnboundScript NanUnboundScript; -typedef v8::Script NanBoundScript; -#endif - -#if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION) -typedef v8::String::ExternalAsciiStringResource - NanExternalOneByteStringResource; -#else -typedef v8::String::ExternalOneByteStringResource - NanExternalOneByteStringResource; -#endif - -#include "nan_new.h" // NOLINT(build/include) - -// uv helpers -#ifdef UV_VERSION_MAJOR -#ifndef UV_VERSION_PATCH -#define UV_VERSION_PATCH 0 -#endif -#define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \ - (UV_VERSION_MINOR << 8) | \ - (UV_VERSION_PATCH)) -#else -#define NAUV_UVVERSION 0x000b00 -#endif - - -#if NAUV_UVVERSION < 0x000b17 -#define NAUV_WORK_CB(func) \ - void func(uv_async_t *async, int) -#else -#define NAUV_WORK_CB(func) \ - void func(uv_async_t *async) -#endif - -// some generic helpers - -template NAN_INLINE bool NanSetPointerSafe( - T *var - , T val -) { - if (var) { - *var = val; - return true; - } else { - return false; - } -} - -template NAN_INLINE T NanGetPointerSafe( - T *var - , T fallback = reinterpret_cast(0) -) { - if (var) { - return *var; - } else { - return fallback; - } -} - -NAN_INLINE bool NanBooleanOptionValue( - v8::Local optionsObj - , v8::Handle opt, bool def -) { - if (def) { - return optionsObj.IsEmpty() - || !optionsObj->Has(opt) - || optionsObj->Get(opt)->BooleanValue(); - } else { - return !optionsObj.IsEmpty() - && optionsObj->Has(opt) - && optionsObj->Get(opt)->BooleanValue(); - } -} - -NAN_INLINE bool NanBooleanOptionValue( - v8::Local optionsObj - , v8::Handle opt -) { - return NanBooleanOptionValue(optionsObj, opt, false); -} - -NAN_INLINE uint32_t NanUInt32OptionValue( - v8::Local optionsObj - , v8::Handle opt - , uint32_t def -) { - return !optionsObj.IsEmpty() - && optionsObj->Has(opt) - && optionsObj->Get(opt)->IsNumber() - ? optionsObj->Get(opt)->Uint32Value() - : def; -} - -template -v8::Local NanNew(v8::Handle); - -template -NAN_INLINE v8::Local _NanEnsureLocal(v8::Handle val) { - return NanNew(val); -} - -template -NAN_INLINE v8::Local _NanEnsureLocal(v8::Local val) { - return val; -} - -/* io.js 1.0 */ -#if NODE_MODULE_VERSION >= IOJS_1_0_MODULE_VERSION \ - || NODE_VERSION_AT_LEAST(0, 11, 15) - NAN_INLINE - void NanSetCounterFunction(v8::CounterLookupCallback cb) { - v8::Isolate::GetCurrent()->SetCounterFunction(cb); - } - - NAN_INLINE - void NanSetCreateHistogramFunction(v8::CreateHistogramCallback cb) { - v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb); - } - - NAN_INLINE - void NanSetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { - v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb); - } - - NAN_INLINE bool NanIdleNotification(int idle_time_in_ms) { - return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms); - } - - NAN_INLINE void NanLowMemoryNotification() { - v8::Isolate::GetCurrent()->LowMemoryNotification(); - } - - NAN_INLINE void NanContextDisposedNotification() { - v8::Isolate::GetCurrent()->ContextDisposedNotification(); - } -#else - NAN_INLINE - void NanSetCounterFunction(v8::CounterLookupCallback cb) { - v8::V8::SetCounterFunction(cb); - } - - NAN_INLINE - void NanSetCreateHistogramFunction(v8::CreateHistogramCallback cb) { - v8::V8::SetCreateHistogramFunction(cb); - } - - NAN_INLINE - void NanSetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { - v8::V8::SetAddHistogramSampleFunction(cb); - } - - NAN_INLINE bool NanIdleNotification(int idle_time_in_ms) { - return v8::V8::IdleNotification(idle_time_in_ms); - } - - NAN_INLINE void NanLowMemoryNotification() { - v8::V8::LowMemoryNotification(); - } - - NAN_INLINE void NanContextDisposedNotification() { - v8::V8::ContextDisposedNotification(); - } -#endif - -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) -// Node 0.11+ (0.11.12 and below won't compile with these) - -# define _NAN_METHOD_ARGS_TYPE const v8::FunctionCallbackInfo& -# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args -# define _NAN_METHOD_RETURN_TYPE void - -# define _NAN_GETTER_ARGS_TYPE const v8::PropertyCallbackInfo& -# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args -# define _NAN_GETTER_RETURN_TYPE void - -# define _NAN_SETTER_ARGS_TYPE const v8::PropertyCallbackInfo& -# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args -# define _NAN_SETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_GETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args -# define _NAN_PROPERTY_GETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_SETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args -# define _NAN_PROPERTY_SETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args -# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE void - -# define _NAN_PROPERTY_DELETER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_DELETER_ARGS \ - _NAN_PROPERTY_DELETER_ARGS_TYPE args -# define _NAN_PROPERTY_DELETER_RETURN_TYPE void - -# define _NAN_PROPERTY_QUERY_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args -# define _NAN_PROPERTY_QUERY_RETURN_TYPE void - -# define _NAN_INDEX_GETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args -# define _NAN_INDEX_GETTER_RETURN_TYPE void - -# define _NAN_INDEX_SETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args -# define _NAN_INDEX_SETTER_RETURN_TYPE void - -# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args -# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE void - -# define _NAN_INDEX_DELETER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args -# define _NAN_INDEX_DELETER_RETURN_TYPE void - -# define _NAN_INDEX_QUERY_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args -# define _NAN_INDEX_QUERY_RETURN_TYPE void - -# define NanScope() v8::HandleScope scope(v8::Isolate::GetCurrent()) -# define NanEscapableScope() \ - v8::EscapableHandleScope scope(v8::Isolate::GetCurrent()) - -# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val)) -# define NanLocker() v8::Locker locker(v8::Isolate::GetCurrent()) -# define NanUnlocker() v8::Unlocker unlocker(v8::Isolate::GetCurrent()) -# define NanReturnValue(value) return args.GetReturnValue().Set(value) -# define NanReturnUndefined() return -# define NanReturnHolder() NanReturnValue(args.Holder()) -# define NanReturnThis() NanReturnValue(args.This()) -# define NanReturnNull() return args.GetReturnValue().SetNull() -# define NanReturnEmptyString() return args.GetReturnValue().SetEmptyString() - -# define NanObjectWrapHandle(obj) obj->handle() - - NAN_INLINE v8::Local NanUndefined() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::Undefined(v8::Isolate::GetCurrent()))); - } - - NAN_INLINE v8::Local NanNull() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::Null(v8::Isolate::GetCurrent()))); - } - - NAN_INLINE v8::Local NanTrue() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::True(v8::Isolate::GetCurrent()))); - } - - NAN_INLINE v8::Local NanFalse() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::False(v8::Isolate::GetCurrent()))); - } - - NAN_INLINE int NanAdjustExternalMemory(int bc) { - return static_cast( - v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc)); - } - - NAN_INLINE void NanSetTemplate( - v8::Handle templ - , const char *name - , v8::Handle value) { - templ->Set(v8::Isolate::GetCurrent(), name, value); - } - - NAN_INLINE void NanSetTemplate( - v8::Handle templ - , v8::Handle name - , v8::Handle value - , v8::PropertyAttribute attributes) { - templ->Set(name, value, attributes); - } - - NAN_INLINE v8::Local NanGetCurrentContext() { - return v8::Isolate::GetCurrent()->GetCurrentContext(); - } - - NAN_INLINE void* NanGetInternalFieldPointer( - v8::Handle object - , int index) { - return object->GetAlignedPointerFromInternalField(index); - } - - NAN_INLINE void NanSetInternalFieldPointer( - v8::Handle object - , int index - , void* value) { - object->SetAlignedPointerInInternalField(index, value); - } - -# define NAN_GC_CALLBACK(name) \ - void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags) - - NAN_INLINE void NanAddGCEpilogueCallback( - v8::Isolate::GCEpilogueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter); - } - - NAN_INLINE void NanRemoveGCEpilogueCallback( - v8::Isolate::GCEpilogueCallback callback) { - v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback); - } - - NAN_INLINE void NanAddGCPrologueCallback( - v8::Isolate::GCPrologueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter); - } - - NAN_INLINE void NanRemoveGCPrologueCallback( - v8::Isolate::GCPrologueCallback callback) { - v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback); - } - - NAN_INLINE void NanGetHeapStatistics( - v8::HeapStatistics *heap_statistics) { - v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics); - } - - NAN_DEPRECATED NAN_INLINE v8::Local NanSymbol( - const char* data, int length = -1) { - return NanNew(data, length); - } - - template - NAN_INLINE void NanAssignPersistent( - v8::Persistent& handle - , v8::Handle obj) { - handle.Reset(v8::Isolate::GetCurrent(), obj); - } - - template - NAN_INLINE void NanAssignPersistent( - v8::Persistent& handle - , const v8::Persistent& obj) { - handle.Reset(v8::Isolate::GetCurrent(), obj); - } - - template - class _NanWeakCallbackData; - - template - struct _NanWeakCallbackInfo { - typedef void (*Callback)(const _NanWeakCallbackData& data); - NAN_INLINE _NanWeakCallbackInfo(v8::Handle handle, P* param, Callback cb) - : parameter(param), callback(cb) { - NanAssignPersistent(persistent, handle); - } - - NAN_INLINE ~_NanWeakCallbackInfo() { - persistent.Reset(); - } - - P* const parameter; - Callback const callback; - v8::Persistent persistent; - }; - - template - class _NanWeakCallbackData { - public: - NAN_INLINE _NanWeakCallbackData(_NanWeakCallbackInfo *info) - : info_(info) { } - - NAN_INLINE v8::Local GetValue() const { - return NanNew(info_->persistent); - } - - NAN_INLINE P* GetParameter() const { return info_->parameter; } - - NAN_INLINE bool IsNearDeath() const { - return info_->persistent.IsNearDeath(); - } - - NAN_INLINE void Revive() const; - - NAN_INLINE _NanWeakCallbackInfo* GetCallbackInfo() const { - return info_; - } - - NAN_DEPRECATED NAN_INLINE void Dispose() const { - } - - private: - _NanWeakCallbackInfo* info_; - }; - - template - static void _NanWeakCallbackDispatcher( - const v8::WeakCallbackData > &data) { - _NanWeakCallbackInfo *info = data.GetParameter(); - _NanWeakCallbackData wcbd(info); - info->callback(wcbd); - if (wcbd.IsNearDeath()) { - delete wcbd.GetCallbackInfo(); - } - } - - template - NAN_INLINE void _NanWeakCallbackData::Revive() const { - info_->persistent.SetWeak(info_, &_NanWeakCallbackDispatcher); - } - -template -NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( - v8::Handle handle - , P* parameter - , typename _NanWeakCallbackInfo::Callback callback) { - _NanWeakCallbackInfo *cbinfo = - new _NanWeakCallbackInfo(handle, parameter, callback); - cbinfo->persistent.SetWeak(cbinfo, &_NanWeakCallbackDispatcher); - return cbinfo; -} - -# define NAN_WEAK_CALLBACK(name) \ - template \ - static void name(const _NanWeakCallbackData &data) - -# define _NAN_ERROR(fun, errmsg) fun(NanNew(errmsg)) - -# define _NAN_THROW_ERROR(fun, errmsg) \ - do { \ - NanScope(); \ - v8::Isolate::GetCurrent()->ThrowException(_NAN_ERROR(fun, errmsg)); \ - } while (0); - - NAN_INLINE v8::Local NanError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::Error, errmsg); - } - - NAN_INLINE void NanThrowError(const char* errmsg) { - _NAN_THROW_ERROR(v8::Exception::Error, errmsg); - } - - NAN_INLINE void NanThrowError(v8::Handle error) { - NanScope(); - v8::Isolate::GetCurrent()->ThrowException(error); - } - - NAN_INLINE v8::Local NanError( - const char *msg - , const int errorNumber - ) { - v8::Local err = v8::Exception::Error(NanNew(msg)); - v8::Local obj = err.As(); - obj->Set(NanNew("code"), NanNew(errorNumber)); - return err; - } - - NAN_INLINE void NanThrowError( - const char *msg - , const int errorNumber - ) { - NanThrowError(NanError(msg, errorNumber)); - } - - NAN_INLINE v8::Local NanTypeError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::TypeError, errmsg); - } - - NAN_INLINE void NanThrowTypeError(const char* errmsg) { - _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); - } - - NAN_INLINE v8::Local NanRangeError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::RangeError, errmsg); - } - - NAN_INLINE void NanThrowRangeError(const char* errmsg) { - _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); - } - - template NAN_INLINE void NanDisposePersistent( - v8::Persistent &handle - ) { - handle.Reset(); - } - - NAN_INLINE v8::Local NanNewBufferHandle ( - char *data - , size_t length - , node::smalloc::FreeCallback callback - , void *hint - ) { - return node::Buffer::New( - v8::Isolate::GetCurrent(), data, length, callback, hint); - } - - NAN_INLINE v8::Local NanNewBufferHandle ( - const char *data - , uint32_t size - ) { - return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); - } - - NAN_INLINE v8::Local NanNewBufferHandle (uint32_t size) { - return node::Buffer::New(v8::Isolate::GetCurrent(), size); - } - - NAN_INLINE v8::Local NanBufferUse( - char* data - , uint32_t size - ) { - return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size); - } - - NAN_INLINE bool NanHasInstance( - const v8::Persistent& function_template - , v8::Handle value - ) { - return NanNew(function_template)->HasInstance(value); - } - - NAN_DEPRECATED NAN_INLINE v8::Local NanNewContextHandle( - v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle() - ) { - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - return v8::Local::New( - isolate - , v8::Context::New(isolate, extensions, tmpl, obj) - ); - } - - NAN_INLINE v8::Local NanCompileScript( - v8::Local s - , const v8::ScriptOrigin& origin - ) { - v8::ScriptCompiler::Source source(s, origin); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); - } - - NAN_INLINE v8::Local NanCompileScript( - v8::Local s - ) { - v8::ScriptCompiler::Source source(s); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); - } - - NAN_INLINE v8::Local NanRunScript( - v8::Handle script - ) { - return script->BindToCurrentContext()->Run(); - } - - NAN_INLINE v8::Local NanRunScript( - v8::Handle script - ) { - return script->Run(); - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , v8::Handle func - , int argc - , v8::Handle* argv) { - return NanNew(node::MakeCallback( - v8::Isolate::GetCurrent(), target, func, argc, argv)); - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , v8::Handle symbol - , int argc - , v8::Handle* argv) { - return NanNew(node::MakeCallback( - v8::Isolate::GetCurrent(), target, symbol, argc, argv)); - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , const char* method - , int argc - , v8::Handle* argv) { - return NanNew(node::MakeCallback( - v8::Isolate::GetCurrent(), target, method, argc, argv)); - } - - template - NAN_INLINE void NanSetIsolateData( - v8::Isolate *isolate - , T *data - ) { - isolate->SetData(0, data); - } - - template - NAN_INLINE T *NanGetIsolateData( - v8::Isolate *isolate - ) { - return static_cast(isolate->GetData(0)); - } - - class NanAsciiString { - public: - NAN_INLINE explicit NanAsciiString(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Length(); - buf = new char[size + 1]; - size = toStr->WriteOneByte(reinterpret_cast(buf)); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - - NAN_INLINE char* operator*() { return buf; } - NAN_INLINE const char* operator*() const { return buf; } - - NAN_INLINE ~NanAsciiString() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanAsciiString(const NanAsciiString&); - void operator=(const NanAsciiString&); - - char *buf; - int size; - }; - - class NanUtf8String { - public: - NAN_INLINE explicit NanUtf8String(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Utf8Length(); - buf = new char[size + 1]; - toStr->WriteUtf8(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - NAN_INLINE char* operator*() { return buf; } - NAN_INLINE const char* operator*() const { return buf; } - - NAN_INLINE ~NanUtf8String() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanUtf8String(const NanUtf8String&); - void operator=(const NanUtf8String&); - - char *buf; - int size; - }; - - class NanUcs2String { - public: - NAN_INLINE explicit NanUcs2String(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Length(); - buf = new uint16_t[size + 1]; - toStr->Write(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - NAN_INLINE uint16_t* operator*() { return buf; } - NAN_INLINE const uint16_t* operator*() const { return buf; } - - NAN_INLINE ~NanUcs2String() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanUcs2String(const NanUcs2String&); - void operator=(const NanUcs2String&); - - uint16_t *buf; - int size; - }; - -#else -// Node 0.8 and 0.10 - -# define _NAN_METHOD_ARGS_TYPE const v8::Arguments& -# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args -# define _NAN_METHOD_RETURN_TYPE v8::Handle - -# define _NAN_GETTER_ARGS_TYPE const v8::AccessorInfo & -# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args -# define _NAN_GETTER_RETURN_TYPE v8::Handle - -# define _NAN_SETTER_ARGS_TYPE const v8::AccessorInfo & -# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args -# define _NAN_SETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_GETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args -# define _NAN_PROPERTY_GETTER_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_SETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args -# define _NAN_PROPERTY_SETTER_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args -# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_DELETER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_DELETER_ARGS _NAN_PROPERTY_DELETER_ARGS_TYPE args -# define _NAN_PROPERTY_DELETER_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_QUERY_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args -# define _NAN_PROPERTY_QUERY_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_GETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args -# define _NAN_INDEX_GETTER_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_SETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args -# define _NAN_INDEX_SETTER_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args -# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_DELETER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args -# define _NAN_INDEX_DELETER_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_QUERY_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args -# define _NAN_INDEX_QUERY_RETURN_TYPE v8::Handle - - NAN_DEPRECATED NAN_INLINE v8::Local NanSymbol( - const char* data, int length = -1) { - return v8::String::NewSymbol(data, length); - } - -# define NanScope() v8::HandleScope scope -# define NanEscapableScope() v8::HandleScope scope -# define NanEscapeScope(val) scope.Close(val) -# define NanLocker() v8::Locker locker -# define NanUnlocker() v8::Unlocker unlocker -# define NanReturnValue(value) return scope.Close(value) -# define NanReturnHolder() NanReturnValue(args.Holder()) -# define NanReturnThis() NanReturnValue(args.This()) -# define NanReturnUndefined() return v8::Undefined() -# define NanReturnNull() return v8::Null() -# define NanReturnEmptyString() return v8::String::Empty() -# define NanObjectWrapHandle(obj) v8::Local::New(obj->handle_) - - NAN_INLINE v8::Local NanUndefined() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::Undefined())); - } - - NAN_INLINE v8::Local NanNull() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::Null())); - } - - NAN_INLINE v8::Local NanTrue() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::True())); - } - - NAN_INLINE v8::Local NanFalse() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::False())); - } - - NAN_INLINE int NanAdjustExternalMemory(int bc) { - return static_cast(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc)); - } - - NAN_INLINE void NanSetTemplate( - v8::Handle templ - , const char *name - , v8::Handle value) { - templ->Set(name, value); - } - - NAN_INLINE void NanSetTemplate( - v8::Handle templ - , v8::Handle name - , v8::Handle value - , v8::PropertyAttribute attributes) { - templ->Set(name, value, attributes); - } - - NAN_INLINE v8::Local NanGetCurrentContext() { - return v8::Context::GetCurrent(); - } - - NAN_INLINE void* NanGetInternalFieldPointer( - v8::Handle object - , int index) { - return object->GetPointerFromInternalField(index); - } - - NAN_INLINE void NanSetInternalFieldPointer( - v8::Handle object - , int index - , void* value) { - object->SetPointerInInternalField(index, value); - } - -# define NAN_GC_CALLBACK(name) \ - void name(v8::GCType type, v8::GCCallbackFlags flags) - - NAN_INLINE void NanAddGCEpilogueCallback( - v8::GCEpilogueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::V8::AddGCEpilogueCallback(callback, gc_type_filter); - } - NAN_INLINE void NanRemoveGCEpilogueCallback( - v8::GCEpilogueCallback callback) { - v8::V8::RemoveGCEpilogueCallback(callback); - } - NAN_INLINE void NanAddGCPrologueCallback( - v8::GCPrologueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::V8::AddGCPrologueCallback(callback, gc_type_filter); - } - NAN_INLINE void NanRemoveGCPrologueCallback( - v8::GCPrologueCallback callback) { - v8::V8::RemoveGCPrologueCallback(callback); - } - NAN_INLINE void NanGetHeapStatistics( - v8::HeapStatistics *heap_statistics) { - v8::V8::GetHeapStatistics(heap_statistics); - } - - template - NAN_INLINE void NanAssignPersistent( - v8::Persistent& handle - , v8::Handle obj) { - handle.Dispose(); - handle = v8::Persistent::New(obj); - } - - template - class _NanWeakCallbackData; - - template - struct _NanWeakCallbackInfo { - typedef void (*Callback)(const _NanWeakCallbackData &data); - NAN_INLINE _NanWeakCallbackInfo(v8::Handle handle, P* param, Callback cb) - : parameter(param) - , callback(cb) - , persistent(v8::Persistent::New(handle)) { } - - NAN_INLINE ~_NanWeakCallbackInfo() { - persistent.Dispose(); - persistent.Clear(); - } - - P* const parameter; - Callback const callback; - v8::Persistent persistent; - }; - - template - class _NanWeakCallbackData { - public: - NAN_INLINE _NanWeakCallbackData(_NanWeakCallbackInfo *info) - : info_(info) { } - - NAN_INLINE v8::Local GetValue() const { - return NanNew(info_->persistent); - } - - NAN_INLINE P* GetParameter() const { return info_->parameter; } - - NAN_INLINE bool IsNearDeath() const { - return info_->persistent.IsNearDeath(); - } - - NAN_INLINE void Revive() const; - - NAN_INLINE _NanWeakCallbackInfo* GetCallbackInfo() const { - return info_; - } - - NAN_DEPRECATED NAN_INLINE void Dispose() const { - } - - private: - _NanWeakCallbackInfo* info_; - }; - - template - static void _NanWeakPersistentDispatcher( - v8::Persistent object, void *data) { - _NanWeakCallbackInfo* info = - static_cast<_NanWeakCallbackInfo*>(data); - _NanWeakCallbackData wcbd(info); - info->callback(wcbd); - if (wcbd.IsNearDeath()) { - delete wcbd.GetCallbackInfo(); - } - } - - template - NAN_INLINE void _NanWeakCallbackData::Revive() const { - info_->persistent.MakeWeak( - info_ - , &_NanWeakPersistentDispatcher); - } - - template - NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( - v8::Handle handle - , P* parameter - , typename _NanWeakCallbackInfo::Callback callback) { - _NanWeakCallbackInfo *cbinfo = - new _NanWeakCallbackInfo(handle, parameter, callback); - cbinfo->persistent.MakeWeak( - cbinfo - , &_NanWeakPersistentDispatcher); - return cbinfo; - } - -# define NAN_WEAK_CALLBACK(name) \ - template \ - static void name(const _NanWeakCallbackData &data) - -# define _NAN_ERROR(fun, errmsg) \ - fun(v8::String::New(errmsg)) - -# define _NAN_THROW_ERROR(fun, errmsg) \ - do { \ - NanScope(); \ - return v8::Local::New( \ - v8::ThrowException(_NAN_ERROR(fun, errmsg))); \ - } while (0); - - NAN_INLINE v8::Local NanError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::Error, errmsg); - } - - NAN_INLINE v8::Local NanThrowError(const char* errmsg) { - _NAN_THROW_ERROR(v8::Exception::Error, errmsg); - } - - NAN_INLINE v8::Local NanThrowError( - v8::Handle error - ) { - NanScope(); - return v8::Local::New(v8::ThrowException(error)); - } - - NAN_INLINE v8::Local NanError( - const char *msg - , const int errorNumber - ) { - v8::Local err = v8::Exception::Error(v8::String::New(msg)); - v8::Local obj = err.As(); - obj->Set(v8::String::New("code"), v8::Int32::New(errorNumber)); - return err; - } - - NAN_INLINE v8::Local NanThrowError( - const char *msg - , const int errorNumber - ) { - return NanThrowError(NanError(msg, errorNumber)); - } - - NAN_INLINE v8::Local NanTypeError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::TypeError, errmsg); - } - - NAN_INLINE v8::Local NanThrowTypeError( - const char* errmsg - ) { - _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); - } - - NAN_INLINE v8::Local NanRangeError( - const char* errmsg - ) { - return _NAN_ERROR(v8::Exception::RangeError, errmsg); - } - - NAN_INLINE v8::Local NanThrowRangeError( - const char* errmsg - ) { - _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); - } - - template - NAN_INLINE void NanDisposePersistent( - v8::Persistent &handle) { // NOLINT(runtime/references) - handle.Dispose(); - handle.Clear(); - } - - NAN_INLINE v8::Local NanNewBufferHandle ( - char *data - , size_t length - , node::Buffer::free_callback callback - , void *hint - ) { - return NanNew( - node::Buffer::New(data, length, callback, hint)->handle_); - } - - NAN_INLINE v8::Local NanNewBufferHandle ( - const char *data - , uint32_t size - ) { -#if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION - return NanNew(node::Buffer::New(data, size)->handle_); -#else - return NanNew( - node::Buffer::New(const_cast(data), size)->handle_); -#endif - } - - NAN_INLINE v8::Local NanNewBufferHandle (uint32_t size) { - return NanNew(node::Buffer::New(size)->handle_); - } - - NAN_INLINE void FreeData(char *data, void *hint) { - delete[] data; - } - - NAN_INLINE v8::Local NanBufferUse( - char* data - , uint32_t size - ) { - return NanNew( - node::Buffer::New(data, size, FreeData, NULL)->handle_); - } - - NAN_INLINE bool NanHasInstance( - const v8::Persistent& function_template - , v8::Handle value - ) { - return function_template->HasInstance(value); - } - - NAN_DEPRECATED NAN_INLINE v8::Local NanNewContextHandle( - v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle() - ) { - v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); - v8::Local lctx = NanNew(ctx); - ctx.Dispose(); - return lctx; - } - - NAN_INLINE v8::Local NanCompileScript( - v8::Local s - , const v8::ScriptOrigin& origin - ) { - return v8::Script::Compile(s, const_cast(&origin)); - } - - NAN_INLINE v8::Local NanCompileScript( - v8::Local s - ) { - return v8::Script::Compile(s); - } - - NAN_INLINE v8::Local NanRunScript(v8::Handle script) { - return script->Run(); - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , v8::Handle func - , int argc - , v8::Handle* argv) { -# if NODE_VERSION_AT_LEAST(0, 8, 0) - return NanNew(node::MakeCallback(target, func, argc, argv)); -# else - v8::TryCatch try_catch; - v8::Local result = func->Call(target, argc, argv); - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - return result; -# endif - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , v8::Handle symbol - , int argc - , v8::Handle* argv) { -# if NODE_VERSION_AT_LEAST(0, 8, 0) - return NanNew(node::MakeCallback(target, symbol, argc, argv)); -# else - v8::Local callback = target->Get(symbol).As(); - return NanMakeCallback(target, callback, argc, argv); -# endif - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , const char* method - , int argc - , v8::Handle* argv) { -# if NODE_VERSION_AT_LEAST(0, 8, 0) - return NanNew(node::MakeCallback(target, method, argc, argv)); -# else - return NanMakeCallback(target, NanNew(method), argc, argv); -# endif - } - - template - NAN_INLINE void NanSetIsolateData( - v8::Isolate *isolate - , T *data - ) { - isolate->SetData(data); - } - - template - NAN_INLINE T *NanGetIsolateData( - v8::Isolate *isolate - ) { - return static_cast(isolate->GetData()); - } - - class NanAsciiString { - public: - NAN_INLINE explicit NanAsciiString(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Length(); - buf = new char[size + 1]; - size = toStr->WriteAscii(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - - NAN_INLINE char* operator*() { return buf; } - NAN_INLINE const char* operator*() const { return buf; } - - NAN_INLINE ~NanAsciiString() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanAsciiString(const NanAsciiString&); - void operator=(const NanAsciiString&); - - char *buf; - int size; - }; - - class NanUtf8String { - public: - NAN_INLINE explicit NanUtf8String(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Utf8Length(); - buf = new char[size + 1]; - toStr->WriteUtf8(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - NAN_INLINE char* operator*() { return buf; } - NAN_INLINE const char* operator*() const { return buf; } - - NAN_INLINE ~NanUtf8String() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanUtf8String(const NanUtf8String&); - void operator=(const NanUtf8String&); - - char *buf; - int size; - }; - - class NanUcs2String { - public: - NAN_INLINE explicit NanUcs2String(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Length(); - buf = new uint16_t[size + 1]; - toStr->Write(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - NAN_INLINE uint16_t* operator*() { return buf; } - NAN_INLINE const uint16_t* operator*() const { return buf; } - - NAN_INLINE ~NanUcs2String() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanUcs2String(const NanUcs2String&); - void operator=(const NanUcs2String&); - - uint16_t *buf; - int size; - }; - -#endif // NODE_MODULE_VERSION - -typedef void (*NanFreeCallback)(char *data, void *hint); - -#define NAN_METHOD(name) _NAN_METHOD_RETURN_TYPE name(_NAN_METHOD_ARGS) -#define NAN_GETTER(name) \ - _NAN_GETTER_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_GETTER_ARGS) -#define NAN_SETTER(name) \ - _NAN_SETTER_RETURN_TYPE name( \ - v8::Local property \ - , v8::Local value \ - , _NAN_SETTER_ARGS) -#define NAN_PROPERTY_GETTER(name) \ - _NAN_PROPERTY_GETTER_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_PROPERTY_GETTER_ARGS) -#define NAN_PROPERTY_SETTER(name) \ - _NAN_PROPERTY_SETTER_RETURN_TYPE name( \ - v8::Local property \ - , v8::Local value \ - , _NAN_PROPERTY_SETTER_ARGS) -#define NAN_PROPERTY_ENUMERATOR(name) \ - _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name(_NAN_PROPERTY_ENUMERATOR_ARGS) -#define NAN_PROPERTY_DELETER(name) \ - _NAN_PROPERTY_DELETER_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_PROPERTY_DELETER_ARGS) -#define NAN_PROPERTY_QUERY(name) \ - _NAN_PROPERTY_QUERY_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_PROPERTY_QUERY_ARGS) -# define NAN_INDEX_GETTER(name) \ - _NAN_INDEX_GETTER_RETURN_TYPE name(uint32_t index, _NAN_INDEX_GETTER_ARGS) -#define NAN_INDEX_SETTER(name) \ - _NAN_INDEX_SETTER_RETURN_TYPE name( \ - uint32_t index \ - , v8::Local value \ - , _NAN_INDEX_SETTER_ARGS) -#define NAN_INDEX_ENUMERATOR(name) \ - _NAN_INDEX_ENUMERATOR_RETURN_TYPE name(_NAN_INDEX_ENUMERATOR_ARGS) -#define NAN_INDEX_DELETER(name) \ - _NAN_INDEX_DELETER_RETURN_TYPE name( \ - uint32_t index \ - , _NAN_INDEX_DELETER_ARGS) -#define NAN_INDEX_QUERY(name) \ - _NAN_INDEX_QUERY_RETURN_TYPE name(uint32_t index, _NAN_INDEX_QUERY_ARGS) - -class NanCallback { - public: - NanCallback() { - NanScope(); - v8::Local obj = NanNew(); - NanAssignPersistent(handle, obj); - } - - explicit NanCallback(const v8::Handle &fn) { - NanScope(); - v8::Local obj = NanNew(); - NanAssignPersistent(handle, obj); - SetFunction(fn); - } - - ~NanCallback() { - if (handle.IsEmpty()) return; - NanDisposePersistent(handle); - } - - NAN_INLINE void SetFunction(const v8::Handle &fn) { - NanScope(); - NanNew(handle)->Set(kCallbackIndex, fn); - } - - NAN_INLINE v8::Local GetFunction() const { - NanEscapableScope(); - return NanEscapeScope(NanNew(handle)->Get(kCallbackIndex) - .As()); - } - - NAN_INLINE bool IsEmpty() const { - NanScope(); - return NanNew(handle)->Get(kCallbackIndex)->IsUndefined(); - } - - NAN_INLINE v8::Handle - Call(v8::Handle target - , int argc - , v8::Handle argv[]) const { -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - return Call_(isolate, target, argc, argv); -#else - return Call_(target, argc, argv); -#endif - } - - NAN_INLINE v8::Handle - Call(int argc, v8::Handle argv[]) const { -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - return Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv); -#else - return Call_(v8::Context::GetCurrent()->Global(), argc, argv); -#endif - } - - private: - v8::Persistent handle; - static const uint32_t kCallbackIndex = 0; - -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - v8::Handle Call_(v8::Isolate *isolate - , v8::Handle target - , int argc - , v8::Handle argv[]) const { -#else - v8::Handle Call_(v8::Handle target - , int argc - , v8::Handle argv[]) const { -#endif - NanEscapableScope(); -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - v8::Local callback = NanNew(handle)-> - Get(kCallbackIndex).As(); - return NanEscapeScope(node::MakeCallback( - isolate - , target - , callback - , argc - , argv - )); -#else -#if NODE_VERSION_AT_LEAST(0, 8, 0) - v8::Local callback = handle-> - Get(kCallbackIndex).As(); - return NanEscapeScope(node::MakeCallback( - target - , callback - , argc - , argv - )); -#else - v8::Local callback = handle-> - Get(kCallbackIndex).As(); - return NanEscapeScope(NanMakeCallback( - target, callback, argc, argv)); -#endif -#endif - } -}; - - -/* abstract */ class NanAsyncWorker { - public: - explicit NanAsyncWorker(NanCallback *callback_) - : callback(callback_), errmsg_(NULL) { - request.data = this; - - NanScope(); - v8::Local obj = NanNew(); - NanAssignPersistent(persistentHandle, obj); - } - - virtual ~NanAsyncWorker() { - NanScope(); - - if (!persistentHandle.IsEmpty()) - NanDisposePersistent(persistentHandle); - if (callback) - delete callback; - if (errmsg_) - delete[] errmsg_; - } - - virtual void WorkComplete() { - NanScope(); - - if (errmsg_ == NULL) - HandleOKCallback(); - else - HandleErrorCallback(); - delete callback; - callback = NULL; - } - - NAN_INLINE void SaveToPersistent( - const char *key, const v8::Local &obj) { - v8::Local handle = NanNew(persistentHandle); - handle->Set(NanNew(key), obj); - } - - v8::Local GetFromPersistent(const char *key) const { - NanEscapableScope(); - v8::Local handle = NanNew(persistentHandle); - return NanEscapeScope(handle->Get(NanNew(key)).As()); - } - - virtual void Execute() = 0; - - uv_work_t request; - - virtual void Destroy() { - delete this; - } - - protected: - v8::Persistent persistentHandle; - NanCallback *callback; - - virtual void HandleOKCallback() { - callback->Call(0, NULL); - } - - virtual void HandleErrorCallback() { - NanScope(); - - v8::Local argv[] = { - v8::Exception::Error(NanNew(ErrorMessage())) - }; - callback->Call(1, argv); - } - - void SetErrorMessage(const char *msg) { - if (errmsg_) { - delete[] errmsg_; - } - - size_t size = strlen(msg) + 1; - errmsg_ = new char[size]; - memcpy(errmsg_, msg, size); - } - - const char* ErrorMessage() const { - return errmsg_; - } - - private: - char *errmsg_; -}; - -/* abstract */ class NanAsyncProgressWorker : public NanAsyncWorker { - public: - explicit NanAsyncProgressWorker(NanCallback *callback_) - : NanAsyncWorker(callback_), asyncdata_(NULL), asyncsize_(0) { - async = new uv_async_t; - uv_async_init( - uv_default_loop() - , async - , AsyncProgress_ - ); - async->data = this; - - uv_mutex_init(&async_lock); - } - - virtual ~NanAsyncProgressWorker() { - uv_mutex_destroy(&async_lock); - - if (asyncdata_) { - delete[] asyncdata_; - } - } - - void WorkProgress() { - uv_mutex_lock(&async_lock); - char *data = asyncdata_; - size_t size = asyncsize_; - asyncdata_ = NULL; - uv_mutex_unlock(&async_lock); - - // Dont send progress events after we've already completed. - if (callback) { - HandleProgressCallback(data, size); - } - delete[] data; - } - - class ExecutionProgress { - friend class NanAsyncProgressWorker; - public: - // You could do fancy generics with templates here. - void Send(const char* data, size_t size) const { - that_->SendProgress_(data, size); - } - - private: - explicit ExecutionProgress(NanAsyncProgressWorker* that) : that_(that) {} - // Prohibit copying and assignment. - ExecutionProgress(const ExecutionProgress&); - void operator=(const ExecutionProgress&); - #if __cplusplus >= 201103L - // Prohibit C++11 move semantics. - ExecutionProgress(ExecutionProgress&&) = delete; - void operator=(ExecutionProgress&&) = delete; - #endif - NanAsyncProgressWorker* const that_; - }; - - virtual void Execute(const ExecutionProgress& progress) = 0; - virtual void HandleProgressCallback(const char *data, size_t size) = 0; - - virtual void Destroy() { - uv_close(reinterpret_cast(async), AsyncClose_); - } - - private: - void Execute() /*final override*/ { - ExecutionProgress progress(this); - Execute(progress); - } - - void SendProgress_(const char *data, size_t size) { - char *new_data = new char[size]; - memcpy(new_data, data, size); - - uv_mutex_lock(&async_lock); - char *old_data = asyncdata_; - asyncdata_ = new_data; - asyncsize_ = size; - uv_mutex_unlock(&async_lock); - - if (old_data) { - delete[] old_data; - } - uv_async_send(async); - } - - NAN_INLINE static NAUV_WORK_CB(AsyncProgress_) { - NanAsyncProgressWorker *worker = - static_cast(async->data); - worker->WorkProgress(); - } - - NAN_INLINE static void AsyncClose_(uv_handle_t* handle) { - NanAsyncProgressWorker *worker = - static_cast(handle->data); - delete reinterpret_cast(handle); - delete worker; - } - - uv_async_t *async; - uv_mutex_t async_lock; - char *asyncdata_; - size_t asyncsize_; -}; - -NAN_INLINE void NanAsyncExecute (uv_work_t* req) { - NanAsyncWorker *worker = static_cast(req->data); - worker->Execute(); -} - -NAN_INLINE void NanAsyncExecuteComplete (uv_work_t* req) { - NanAsyncWorker* worker = static_cast(req->data); - worker->WorkComplete(); - worker->Destroy(); -} - -NAN_INLINE void NanAsyncQueueWorker (NanAsyncWorker* worker) { - uv_queue_work( - uv_default_loop() - , &worker->request - , NanAsyncExecute - , (uv_after_work_cb)NanAsyncExecuteComplete - ); -} - -//// Base 64 //// - -#define _nan_base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) - -// Doesn't check for padding at the end. Can be 1-2 bytes over. -NAN_INLINE size_t _nan_base64_decoded_size_fast(size_t size) { - size_t remainder = size % 4; - - size = (size / 4) * 3; - if (remainder) { - if (size == 0 && remainder == 1) { - // special case: 1-byte input cannot be decoded - size = 0; - } else { - // non-padded input, add 1 or 2 extra bytes - size += 1 + (remainder == 3); - } - } - - return size; -} - -template -NAN_INLINE size_t _nan_base64_decoded_size( - const T* src - , size_t size -) { - if (size == 0) - return 0; - - if (src[size - 1] == '=') - size--; - if (size > 0 && src[size - 1] == '=') - size--; - - return _nan_base64_decoded_size_fast(size); -} - -// supports regular and URL-safe base64 -static const int _nan_unbase64_table[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63 - , 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1 - , -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 - , 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63 - , -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 - , 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 -}; - -#define _nan_unbase64(x) _nan_unbase64_table[(uint8_t)(x)] - -template static size_t _nan_base64_decode( - char* buf - , size_t len - , const T* src - , const size_t srcLen -) { - char* dst = buf; - char* dstEnd = buf + len; - const T* srcEnd = src + srcLen; - - while (src < srcEnd && dst < dstEnd) { - ptrdiff_t remaining = srcEnd - src; - char a, b, c, d; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining == 0 || *src == '=') break; - a = _nan_unbase64(*src++); - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 1 || *src == '=') break; - b = _nan_unbase64(*src++); - - *dst++ = (a << 2) | ((b & 0x30) >> 4); - if (dst == dstEnd) break; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 2 || *src == '=') break; - c = _nan_unbase64(*src++); - - *dst++ = ((b & 0x0F) << 4) | ((c & 0x3C) >> 2); - if (dst == dstEnd) break; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 3 || *src == '=') break; - d = _nan_unbase64(*src++); - - *dst++ = ((c & 0x03) << 6) | (d & 0x3F); - } - - return dst - buf; -} - -//// HEX //// - -template unsigned _nan_hex2bin(T c) { - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); - if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); - return static_cast(-1); -} - -template static size_t _nan_hex_decode( - char* buf - , size_t len - , const T* src - , const size_t srcLen -) { - size_t i; - for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) { - unsigned a = _nan_hex2bin(src[i * 2 + 0]); - unsigned b = _nan_hex2bin(src[i * 2 + 1]); - if (!~a || !~b) return i; - buf[i] = a * 16 + b; - } - - return i; -} - -namespace NanIntern { - -inline -NanExternalOneByteStringResource const* -GetExternalResource(v8::Local str) { -#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION - return str->GetExternalAsciiStringResource(); -#else - return str->GetExternalOneByteStringResource(); -#endif -} - -inline -bool -IsExternal(v8::Local str) { -#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION - return str->IsExternalAscii(); -#else - return str->IsExternalOneByte(); -#endif -} - -} // end of namespace NanIntern - -static bool _NanGetExternalParts( - v8::Handle val - , const char** data - , size_t* len -) { - if (node::Buffer::HasInstance(val)) { - *data = node::Buffer::Data(val.As()); - *len = node::Buffer::Length(val.As()); - return true; - } - - assert(val->IsString()); - v8::Local str = NanNew(val.As()); - - if (NanIntern::IsExternal(str)) { - const NanExternalOneByteStringResource* ext; - ext = NanIntern::GetExternalResource(str); - *data = ext->data(); - *len = ext->length(); - return true; - } - - if (str->IsExternal()) { - const v8::String::ExternalStringResource* ext; - ext = str->GetExternalStringResource(); - *data = reinterpret_cast(ext->data()); - *len = ext->length(); - return true; - } - - return false; -} - -namespace Nan { - enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; -} - -#if !NODE_VERSION_AT_LEAST(0, 10, 0) -# include "nan_string_bytes.h" // NOLINT(build/include) -#endif - -NAN_INLINE v8::Local NanEncode( - const void *buf, size_t len, enum Nan::Encoding encoding = Nan::BINARY) { -#if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION) - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - node::encoding node_enc = static_cast(encoding); - - if (encoding == Nan::UCS2) { - return node::Encode( - isolate - , reinterpret_cast(buf) - , len / 2); - } else { - return node::Encode( - isolate - , reinterpret_cast(buf) - , len - , node_enc); - } -#elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - return node::Encode( - v8::Isolate::GetCurrent() - , buf, len - , static_cast(encoding)); -#else -# if NODE_VERSION_AT_LEAST(0, 10, 0) - return node::Encode(buf, len, static_cast(encoding)); -# else - return NanIntern::Encode(reinterpret_cast(buf), len, encoding); -# endif -#endif -} - -NAN_INLINE ssize_t NanDecodeBytes( - v8::Handle val, enum Nan::Encoding encoding = Nan::BINARY) { -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - return node::DecodeBytes( - v8::Isolate::GetCurrent() - , val - , static_cast(encoding)); -#else -# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) - if (encoding == Nan::BUFFER) { - return node::DecodeBytes(val, node::BINARY); - } -# endif - return node::DecodeBytes(val, static_cast(encoding)); -#endif -} - -NAN_INLINE ssize_t NanDecodeWrite( - char *buf - , size_t len - , v8::Handle val - , enum Nan::Encoding encoding = Nan::BINARY) { -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - return node::DecodeWrite( - v8::Isolate::GetCurrent() - , buf - , len - , val - , static_cast(encoding)); -#else -# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) - if (encoding == Nan::BUFFER) { - return node::DecodeWrite(buf, len, val, node::BINARY); - } -# endif - return node::DecodeWrite( - buf - , len - , val - , static_cast(encoding)); -#endif -} - -/* NAN_DEPRECATED */ NAN_INLINE void* _NanRawString( - v8::Handle from - , enum Nan::Encoding encoding - , size_t *datalen - , void *buf - , size_t buflen - , int flags -) { - NanScope(); - - size_t sz_; - size_t term_len = !(flags & v8::String::NO_NULL_TERMINATION); - char *data = NULL; - size_t len; - bool is_extern = _NanGetExternalParts( - from - , const_cast(&data) - , &len); - - if (is_extern && !term_len) { - NanSetPointerSafe(datalen, len); - return data; - } - - v8::Local toStr = from->ToString(); - - char *to = static_cast(buf); - - switch (encoding) { - case Nan::ASCII: -#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , toStr->WriteAscii(to, 0, static_cast(sz_ + term_len), flags)); - return to; -#endif - case Nan::BINARY: - case Nan::BUFFER: - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } -#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION - { - uint16_t* twobytebuf = new uint16_t[sz_ + term_len]; - - size_t somelen = toStr->Write(twobytebuf, 0, - static_cast(sz_ + term_len), flags); - - for (size_t i = 0; i < sz_ + term_len && i < somelen + term_len; i++) { - unsigned char *b = reinterpret_cast(&twobytebuf[i]); - to[i] = *b; - } - - NanSetPointerSafe(datalen, somelen); - - delete[] twobytebuf; - return to; - } -#else - NanSetPointerSafe( - datalen, - toStr->WriteOneByte( - reinterpret_cast(to) - , 0 - , static_cast(sz_ + term_len) - , flags)); - return to; -#endif - case Nan::UTF8: - sz_ = toStr->Utf8Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , toStr->WriteUtf8(to, static_cast(sz_ + term_len) - , NULL, flags) - - term_len); - return to; - case Nan::BASE64: - { - v8::String::Value value(toStr); - sz_ = _nan_base64_decoded_size(*value, value.length()); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len); - } - NanSetPointerSafe( - datalen - , _nan_base64_decode(to, sz_, *value, value.length())); - if (term_len) { - to[sz_] = '\0'; - } - return to; - } - case Nan::UCS2: - { - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[(sz_ + term_len) * 2]; - } else { - assert(buflen >= (sz_ + term_len) * 2 && "too small buffer"); - } - - int bc = 2 * toStr->Write( - reinterpret_cast(to) - , 0 - , static_cast(sz_ + term_len) - , flags); - NanSetPointerSafe(datalen, bc); - return to; - } - case Nan::HEX: - { - v8::String::Value value(toStr); - sz_ = value.length(); - assert(!(sz_ & 1) && "bad hex data"); - if (to == NULL) { - to = new char[sz_ / 2 + term_len]; - } else { - assert(buflen >= sz_ / 2 + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , _nan_hex_decode(to, sz_ / 2, *value, value.length())); - } - if (term_len) { - to[sz_ / 2] = '\0'; - } - return to; - default: - assert(0 && "unknown encoding"); - } - return to; -} - -NAN_DEPRECATED NAN_INLINE void* NanRawString( - v8::Handle from - , enum Nan::Encoding encoding - , size_t *datalen - , void *buf - , size_t buflen - , int flags -) { - return _NanRawString(from, encoding, datalen, buf, buflen, flags); -} - - -NAN_DEPRECATED NAN_INLINE char* NanCString( - v8::Handle from - , size_t *datalen - , char *buf = NULL - , size_t buflen = 0 - , int flags = v8::String::NO_OPTIONS -) { - return static_cast( - _NanRawString(from, Nan::UTF8, datalen, buf, buflen, flags) - ); -} - -NAN_INLINE void NanSetPrototypeTemplate( - v8::Local templ - , const char *name - , v8::Handle value -) { - NanSetTemplate(templ->PrototypeTemplate(), name, value); -} - -NAN_INLINE void NanSetPrototypeTemplate( - v8::Local templ - , v8::Handle name - , v8::Handle value - , v8::PropertyAttribute attributes -) { - NanSetTemplate(templ->PrototypeTemplate(), name, value, attributes); -} - -NAN_INLINE void NanSetInstanceTemplate( - v8::Local templ - , const char *name - , v8::Handle value -) { - NanSetTemplate(templ->InstanceTemplate(), name, value); -} - -NAN_INLINE void NanSetInstanceTemplate( - v8::Local templ - , v8::Handle name - , v8::Handle value - , v8::PropertyAttribute attributes -) { - NanSetTemplate(templ->InstanceTemplate(), name, value, attributes); -} - -//=== Export ================================================================== - -inline -void -NanExport(v8::Handle target, const char * name, - NanFunctionCallback f) { - target->Set(NanNew(name), - NanNew(f)->GetFunction()); -} - -//=== Tap Reverse Binding ===================================================== - -struct NanTap { - explicit NanTap(v8::Handle t) : t_() { - NanAssignPersistent(t_, t->ToObject()); - } - - ~NanTap() { NanDisposePersistent(t_); } // not sure if neccessary - - inline void plan(int i) { - v8::Handle arg = NanNew(i); - NanMakeCallback(NanNew(t_), "plan", 1, &arg); - } - - inline void ok(bool isOk, const char * msg = NULL) { - v8::Handle args[2]; - args[0] = NanNew(isOk); - if (msg) args[1] = NanNew(msg); - NanMakeCallback(NanNew(t_), "ok", msg ? 2 : 1, args); - } - - private: - v8::Persistent t_; -}; - -#define NAN_STRINGIZE2(x) #x -#define NAN_STRINGIZE(x) NAN_STRINGIZE2(x) -#define NAN_TEST_EXPRESSION(expression) \ - ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression - -#define return_NanValue(v) NanReturnValue(v) -#define return_NanUndefined() NanReturnUndefined() -#define NAN_EXPORT(target, function) NanExport(target, #function, function) - -#endif // NAN_H_ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_12_inl.h b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_12_inl.h deleted file mode 100755 index ff63ec0c..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_12_inl.h +++ /dev/null @@ -1,262 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2015 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_IMPLEMENTATION_12_INL_H_ -#define NAN_IMPLEMENTATION_12_INL_H_ -//============================================================================== -// node v0.11 implementation -//============================================================================== - -#if defined(_MSC_VER) -# pragma warning( disable : 4530 ) -# include -# pragma warning( default : 4530 ) -#else -# include -#endif - -namespace NanIntern { - -//=== Array ==================================================================== - -Factory::return_t -Factory::New() { - return v8::Array::New(v8::Isolate::GetCurrent()); -} - -Factory::return_t -Factory::New(int length) { - return v8::Array::New(v8::Isolate::GetCurrent(), length); -} - -//=== Boolean ================================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::Boolean::New(v8::Isolate::GetCurrent(), value); -} - -//=== Boolean Object =========================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::BooleanObject::New(value).As(); -} - -//=== Context ================================================================== - -Factory::return_t -Factory::New( v8::ExtensionConfiguration* extensions - , v8::Handle tmpl - , v8::Handle obj) { - return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj); -} - -//=== Date ===================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Date::New(v8::Isolate::GetCurrent(), value).As(); -} - -//=== External ================================================================= - -Factory::return_t -Factory::New(void * value) { - return v8::External::New(v8::Isolate::GetCurrent(), value); -} - -//=== Function ================================================================= - -Factory::return_t -Factory::New( NanFunctionCallback callback - , v8::Handle data) { - return v8::Function::New( v8::Isolate::GetCurrent() - , callback - , data); -} - -//=== Function Template ======================================================== - -Factory::return_t -Factory::New( NanFunctionCallback callback - , v8::Handle data - , v8::Handle signature) { - return v8::FunctionTemplate::New( v8::Isolate::GetCurrent() - , callback - , data - , signature); -} - -//=== Number =================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Number::New(v8::Isolate::GetCurrent(), value); -} - -//=== Number Object ============================================================ - -Factory::return_t -Factory::New(double value) { - return v8::NumberObject::New( v8::Isolate::GetCurrent() - , value).As(); -} - -//=== Integer, Int32 and Uint32 ================================================ - -template -typename IntegerFactory::return_t -IntegerFactory::New(int32_t value) { - return To(T::New(v8::Isolate::GetCurrent(), value)); -} - -template -typename IntegerFactory::return_t -IntegerFactory::New(uint32_t value) { - return To(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -Factory::return_t -Factory::New(int32_t value) { - return To( - v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -Factory::return_t -Factory::New(uint32_t value) { - return To( - v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -//=== Object =================================================================== - -Factory::return_t -Factory::New() { - return v8::Object::New(v8::Isolate::GetCurrent()); -} - -//=== Object Template ========================================================== - -Factory::return_t -Factory::New() { - return v8::ObjectTemplate::New(v8::Isolate::GetCurrent()); -} - -//=== RegExp =================================================================== - -Factory::return_t -Factory::New( - v8::Handle pattern - , v8::RegExp::Flags flags) { - return v8::RegExp::New(pattern, flags); -} - -//=== Script =================================================================== - -Factory::return_t -Factory::New( v8::Local source) { - v8::ScriptCompiler::Source src(source); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::ScriptCompiler::Source src(source, origin); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); -} - -//=== Signature ================================================================ - -Factory::return_t -Factory::New( Factory::FTH receiver - , int argc - , Factory::FTH argv[]) { - return v8::Signature::New(v8::Isolate::GetCurrent(), receiver, argc, argv); -} - -//=== String =================================================================== - -Factory::return_t -Factory::New() { - return v8::String::Empty(v8::Isolate::GetCurrent()); -} - -Factory::return_t -Factory::New(const char * value, int length) { - return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New(std::string const& value) { - assert(value.size() <= INT_MAX && "string too long"); - return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), - value.data(), v8::String::kNormalString, static_cast(value.size())); -} - -Factory::return_t -Factory::New(const uint8_t * value, int length) { - return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New(const uint16_t * value, int length) { - return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New(v8::String::ExternalStringResource * value) { - return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); -} - -Factory::return_t -Factory::New(NanExternalOneByteStringResource * value) { - return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); -} - -//=== String Object ============================================================ - -Factory::return_t -Factory::New(v8::Handle value) { - return v8::StringObject::New(value).As(); -} - -//=== Unbound Script =========================================================== - -Factory::return_t -Factory::New(v8::Local source) { - v8::ScriptCompiler::Source src(source); - return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::ScriptCompiler::Source src(source, origin); - return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); -} - -} // end of namespace NanIntern - -//=== Presistents and Handles ================================================== - -template -inline v8::Local NanNew(v8::Handle h) { - return v8::Local::New(v8::Isolate::GetCurrent(), h); -} - -template -inline v8::Local NanNew(v8::Persistent const& p) { - return v8::Local::New(v8::Isolate::GetCurrent(), p); -} - -#endif // NAN_IMPLEMENTATION_12_INL_H_ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_pre_12_inl.h b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_pre_12_inl.h deleted file mode 100755 index 85dd2754..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_pre_12_inl.h +++ /dev/null @@ -1,268 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2015 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_ -#define NAN_IMPLEMENTATION_PRE_12_INL_H_ - -#include - -#if defined(_MSC_VER) -# pragma warning( disable : 4530 ) -# include -# include -# pragma warning( default : 4530 ) -#else -# include -# include -#endif - -//============================================================================== -// node v0.10 implementation -//============================================================================== - -namespace NanIntern { - -//=== Array ==================================================================== - -Factory::return_t -Factory::New() { - return v8::Array::New(); -} - -Factory::return_t -Factory::New(int length) { - return v8::Array::New(length); -} - -//=== Boolean ================================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::Boolean::New(value)->ToBoolean(); -} - -//=== Boolean Object =========================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::BooleanObject::New(value).As(); -} - -//=== Context ================================================================== - -Factory::return_t -Factory::New( v8::ExtensionConfiguration* extensions - , v8::Handle tmpl - , v8::Handle obj) { - v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); - v8::Local lctx = v8::Local::New(ctx); - ctx.Dispose(); - return lctx; -} - -//=== Date ===================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Date::New(value).As(); -} - -//=== External ================================================================= - -Factory::return_t -Factory::New(void * value) { - return v8::External::New(value); -} - -//=== Function ================================================================= - -Factory::return_t -Factory::New( NanFunctionCallback callback - , v8::Handle data) { - return Factory::New( callback - , data - , v8::Handle() - )->GetFunction(); -} - - -//=== FunctionTemplate ========================================================= - -Factory::return_t -Factory::New( NanFunctionCallback callback - , v8::Handle data - , v8::Handle signature) { - // Note(agnat): Emulate length argument here. Unfortunately, I couldn't find - // a way. Have at it though... - return v8::FunctionTemplate::New( callback - , data - , signature); -} - -//=== Number =================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Number::New(value); -} - -//=== Number Object ============================================================ - -Factory::return_t -Factory::New(double value) { - return v8::NumberObject::New(value).As(); -} - -//=== Integer, Int32 and Uint32 ================================================ - -template -typename IntegerFactory::return_t -IntegerFactory::New(int32_t value) { - return To(T::New(value)); -} - -template -typename IntegerFactory::return_t -IntegerFactory::New(uint32_t value) { - return To(T::NewFromUnsigned(value)); -} - -Factory::return_t -Factory::New(int32_t value) { - return To(v8::Uint32::NewFromUnsigned(value)); -} - -Factory::return_t -Factory::New(uint32_t value) { - return To(v8::Uint32::NewFromUnsigned(value)); -} - - -//=== Object =================================================================== - -Factory::return_t -Factory::New() { - return v8::Object::New(); -} - -//=== Object Template ========================================================== - -Factory::return_t -Factory::New() { - return v8::ObjectTemplate::New(); -} - -//=== RegExp =================================================================== - -Factory::return_t -Factory::New( - v8::Handle pattern - , v8::RegExp::Flags flags) { - return v8::RegExp::New(pattern, flags); -} - -//=== Script =================================================================== - -Factory::return_t -Factory::New( v8::Local source) { - return v8::Script::New(source); -} -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - return v8::Script::New(source, const_cast(&origin)); -} - -//=== Signature ================================================================ - -Factory::return_t -Factory::New( Factory::FTH receiver - , int argc - , Factory::FTH argv[]) { - return v8::Signature::New(receiver, argc, argv); -} - -//=== String =================================================================== - -Factory::return_t -Factory::New() { - return v8::String::Empty(); -} - -Factory::return_t -Factory::New(const char * value, int length) { - return v8::String::New(value, length); -} - -Factory::return_t -Factory::New(std::string const& value) { - assert(value.size() <= INT_MAX && "string too long"); - return v8::String::New( value.data(), static_cast(value.size())); -} - -inline -void -widenString(std::vector *ws, const uint8_t *s, int l = -1) { - size_t len = static_cast(l); - if (l < 0) { - len = strlen(reinterpret_cast(s)); - } - assert(len <= INT_MAX && "string too long"); - ws->resize(len); - std::copy(s, s + len, ws->begin()); -} - -Factory::return_t -Factory::New(const uint16_t * value, int length) { - return v8::String::New(value, length); -} - -Factory::return_t -Factory::New(const uint8_t * value, int length) { - std::vector wideString; - widenString(&wideString, value, length); - if (wideString.size() == 0) { - return v8::String::Empty(); - } else { - return v8::String::New(&wideString.front() - , static_cast(wideString.size())); - } -} - -Factory::return_t -Factory::New(v8::String::ExternalStringResource * value) { - return v8::String::NewExternal(value); -} - -Factory::return_t -Factory::New(v8::String::ExternalAsciiStringResource * value) { - return v8::String::NewExternal(value); -} - -//=== String Object ============================================================ - -Factory::return_t -Factory::New(v8::Handle value) { - return v8::StringObject::New(value).As(); -} - -} // end of namespace NanIntern - -//=== Presistents and Handles ================================================== - -template -inline v8::Local NanNew(v8::Handle h) { - return v8::Local::New(h); -} - -template -inline v8::Local NanNew(v8::Persistent const& p) { - return v8::Local::New(p); -} - -#endif // NAN_IMPLEMENTATION_PRE_12_INL_H_ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_new.h b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_new.h deleted file mode 100755 index 95b6b51e..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_new.h +++ /dev/null @@ -1,329 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2015 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_NEW_H_ -#define NAN_NEW_H_ - -#if defined(_MSC_VER) -# pragma warning( disable : 4530 ) -# include -# pragma warning( default : 4530 ) -#else -# include -#endif - -namespace NanIntern { // scnr - -// TODO(agnat): Generalize -template v8::Local To(v8::Handle i); - -template <> -inline -v8::Local -To(v8::Handle i) { return i->ToInteger(); } - -template <> -inline -v8::Local -To(v8::Handle i) { return i->ToInt32(); } - -template <> -inline -v8::Local -To(v8::Handle i) { return i->ToUint32(); } - -template struct FactoryBase { typedef v8::Local return_t; }; - -template struct Factory; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); - static inline return_t New(int length); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(bool value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(bool value); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle()); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(void *value); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( NanFunctionCallback callback - , v8::Handle data = v8::Handle()); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( NanFunctionCallback callback = NULL - , v8::Handle data = v8::Handle() - , v8::Handle signature = v8::Handle()); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template -struct IntegerFactory : FactoryBase { - typedef typename FactoryBase::return_t return_t; - static inline return_t New(int32_t value); - static inline return_t New(uint32_t value); -}; - -template <> -struct Factory : IntegerFactory {}; - -template <> -struct Factory : IntegerFactory {}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(int32_t value); - static inline return_t New(uint32_t value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New( - v8::Handle pattern, v8::RegExp::Flags flags); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New( v8::Local source); - static inline return_t New( v8::Local source - , v8::ScriptOrigin const& origin); -}; - -template <> -struct Factory : FactoryBase { - typedef v8::Handle FTH; - static inline - return_t - New( FTH receiver = FTH(), int argc = 0, FTH argv[] = NULL ); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); - static inline return_t New(const char *value, int length = -1); - static inline return_t New(const uint16_t *value, int length = -1); - static inline return_t New(std::string const& value); - - static inline return_t New(v8::String::ExternalStringResource * value); - static inline return_t New(NanExternalOneByteStringResource * value); - - // TODO(agnat): Deprecate. - static inline return_t New(const uint8_t * value, int length = -1); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(v8::Handle value); -}; - -} // end of namespace NanIntern - -#if (NODE_MODULE_VERSION >= 12) - -namespace NanIntern { - -template <> -struct Factory : FactoryBase { - static inline return_t New( v8::Local source); - static inline return_t New( v8::Local source - , v8::ScriptOrigin const& origin); -}; - -} // end of namespace NanIntern - -# include "nan_implementation_12_inl.h" - -#else // NODE_MODULE_VERSION >= 12 - -# include "nan_implementation_pre_12_inl.h" - -#endif - -//=== API ====================================================================== - -template -typename NanIntern::Factory::return_t -NanNew() { - return NanIntern::Factory::New(); -} - -template -typename NanIntern::Factory::return_t -NanNew(A0 arg0) { - return NanIntern::Factory::New(arg0); -} - -template -typename NanIntern::Factory::return_t -NanNew(A0 arg0, A1 arg1) { - return NanIntern::Factory::New(arg0, arg1); -} - -template -typename NanIntern::Factory::return_t -NanNew(A0 arg0, A1 arg1, A2 arg2) { - return NanIntern::Factory::New(arg0, arg1, arg2); -} - -template -typename NanIntern::Factory::return_t -NanNew(A0 arg0, A1 arg1, A2 arg2, A3 arg3) { - return NanIntern::Factory::New(arg0, arg1, arg2, arg3); -} - -// Note(agnat): When passing overloaded function pointers to template functions -// as generic arguments the compiler needs help in picking the right overload. -// These two functions handle NanNew and NanNew with -// all argument variations. - -// v8::Function and v8::FunctionTemplate with one or two arguments -template -typename NanIntern::Factory::return_t -NanNew( NanFunctionCallback callback - , v8::Handle data = v8::Handle()) { - return NanIntern::Factory::New(callback, data); -} - -// v8::Function and v8::FunctionTemplate with three arguments -template -typename NanIntern::Factory::return_t -NanNew( NanFunctionCallback callback - , v8::Handle data = v8::Handle() - , A2 a2 = A2()) { - return NanIntern::Factory::New(callback, data, a2); -} - -// Convenience - -template inline v8::Local NanNew(v8::Handle h); -template inline v8::Local NanNew(v8::Persistent const& p); - -inline -NanIntern::Factory::return_t -NanNew(bool value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(int32_t value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(uint32_t value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(double value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(std::string const& value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(const char * value, int length) { - return NanNew(value, length); -} - -inline -NanIntern::Factory::return_t -NanNew(const char * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(const uint8_t * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(const uint16_t * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(v8::String::ExternalStringResource * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(NanExternalOneByteStringResource * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(v8::Handle pattern, v8::RegExp::Flags flags) { - return NanNew(pattern, flags); -} - -#endif // NAN_NEW_H_ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_string_bytes.h b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_string_bytes.h deleted file mode 100755 index 9deecfbb..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_string_bytes.h +++ /dev/null @@ -1,312 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -#ifndef NAN_STRING_BYTES_H_ -#define NAN_STRING_BYTES_H_ - -// Decodes a v8::Handle or Buffer to a raw char* - -#include -#include -#include -#include // memcpy -#include - -namespace NanIntern { - -using v8::Local; -using v8::Handle; -using v8::Object; -using v8::String; -using v8::Value; - - -//// Base 64 //// - -#define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) - - - -//// Nan::HEX //// - -static bool contains_non_ascii_slow(const char* buf, size_t len) { - for (size_t i = 0; i < len; ++i) { - if (buf[i] & 0x80) return true; - } - return false; -} - - -static bool contains_non_ascii(const char* src, size_t len) { - if (len < 16) { - return contains_non_ascii_slow(src, len); - } - - const unsigned bytes_per_word = sizeof(void*); - const unsigned align_mask = bytes_per_word - 1; - const unsigned unaligned = reinterpret_cast(src) & align_mask; - - if (unaligned > 0) { - const unsigned n = bytes_per_word - unaligned; - if (contains_non_ascii_slow(src, n)) return true; - src += n; - len -= n; - } - - -#if defined(__x86_64__) || defined(_WIN64) - const uintptr_t mask = 0x8080808080808080ll; -#else - const uintptr_t mask = 0x80808080l; -#endif - - const uintptr_t* srcw = reinterpret_cast(src); - - for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { - if (srcw[i] & mask) return true; - } - - const unsigned remainder = len & align_mask; - if (remainder > 0) { - const size_t offset = len - remainder; - if (contains_non_ascii_slow(src + offset, remainder)) return true; - } - - return false; -} - - -static void force_ascii_slow(const char* src, char* dst, size_t len) { - for (size_t i = 0; i < len; ++i) { - dst[i] = src[i] & 0x7f; - } -} - - -static void force_ascii(const char* src, char* dst, size_t len) { - if (len < 16) { - force_ascii_slow(src, dst, len); - return; - } - - const unsigned bytes_per_word = sizeof(void*); - const unsigned align_mask = bytes_per_word - 1; - const unsigned src_unalign = reinterpret_cast(src) & align_mask; - const unsigned dst_unalign = reinterpret_cast(dst) & align_mask; - - if (src_unalign > 0) { - if (src_unalign == dst_unalign) { - const unsigned unalign = bytes_per_word - src_unalign; - force_ascii_slow(src, dst, unalign); - src += unalign; - dst += unalign; - len -= src_unalign; - } else { - force_ascii_slow(src, dst, len); - return; - } - } - -#if defined(__x86_64__) || defined(_WIN64) - const uintptr_t mask = ~0x8080808080808080ll; -#else - const uintptr_t mask = ~0x80808080l; -#endif - - const uintptr_t* srcw = reinterpret_cast(src); - uintptr_t* dstw = reinterpret_cast(dst); - - for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { - dstw[i] = srcw[i] & mask; - } - - const unsigned remainder = len & align_mask; - if (remainder > 0) { - const size_t offset = len - remainder; - force_ascii_slow(src + offset, dst + offset, remainder); - } -} - - -static size_t base64_encode(const char* src, - size_t slen, - char* dst, - size_t dlen) { - // We know how much we'll write, just make sure that there's space. - assert(dlen >= base64_encoded_size(slen) && - "not enough space provided for base64 encode"); - - dlen = base64_encoded_size(slen); - - unsigned a; - unsigned b; - unsigned c; - unsigned i; - unsigned k; - unsigned n; - - static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - - i = 0; - k = 0; - n = slen / 3 * 3; - - while (i < n) { - a = src[i + 0] & 0xff; - b = src[i + 1] & 0xff; - c = src[i + 2] & 0xff; - - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; - dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)]; - dst[k + 3] = table[c & 0x3f]; - - i += 3; - k += 4; - } - - if (n != slen) { - switch (slen - n) { - case 1: - a = src[i + 0] & 0xff; - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[(a & 3) << 4]; - dst[k + 2] = '='; - dst[k + 3] = '='; - break; - - case 2: - a = src[i + 0] & 0xff; - b = src[i + 1] & 0xff; - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; - dst[k + 2] = table[(b & 0x0f) << 2]; - dst[k + 3] = '='; - break; - } - } - - return dlen; -} - - -static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) { - // We know how much we'll write, just make sure that there's space. - assert(dlen >= slen * 2 && - "not enough space provided for hex encode"); - - dlen = slen * 2; - for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) { - static const char hex[] = "0123456789abcdef"; - uint8_t val = static_cast(src[i]); - dst[k + 0] = hex[val >> 4]; - dst[k + 1] = hex[val & 15]; - } - - return dlen; -} - - - -static Local Encode(const char* buf, - size_t buflen, - enum Nan::Encoding encoding) { - assert(buflen <= node::Buffer::kMaxLength); - if (!buflen && encoding != Nan::BUFFER) - return NanNew(""); - - Local val; - switch (encoding) { - case Nan::BUFFER: - return NanNewBufferHandle(buf, buflen); - - case Nan::ASCII: - if (contains_non_ascii(buf, buflen)) { - char* out = new char[buflen]; - force_ascii(buf, out, buflen); - val = NanNew(out, buflen); - delete[] out; - } else { - val = NanNew(buf, buflen); - } - break; - - case Nan::UTF8: - val = NanNew(buf, buflen); - break; - - case Nan::BINARY: { - // TODO(isaacs) use ExternalTwoByteString? - const unsigned char *cbuf = reinterpret_cast(buf); - uint16_t * twobytebuf = new uint16_t[buflen]; - for (size_t i = 0; i < buflen; i++) { - // XXX is the following line platform independent? - twobytebuf[i] = cbuf[i]; - } - val = NanNew(twobytebuf, buflen); - delete[] twobytebuf; - break; - } - - case Nan::BASE64: { - size_t dlen = base64_encoded_size(buflen); - char* dst = new char[dlen]; - - size_t written = base64_encode(buf, buflen, dst, dlen); - assert(written == dlen); - - val = NanNew(dst, dlen); - delete[] dst; - break; - } - - case Nan::UCS2: { - const uint16_t* data = reinterpret_cast(buf); - val = NanNew(data, buflen / 2); - break; - } - - case Nan::HEX: { - size_t dlen = buflen * 2; - char* dst = new char[dlen]; - size_t written = hex_encode(buf, buflen, dst, dlen); - assert(written == dlen); - - val = NanNew(dst, dlen); - delete[] dst; - break; - } - - default: - assert(0 && "unknown encoding"); - break; - } - - return val; -} - -#undef base64_encoded_size - -} // namespace NanIntern - -#endif // NAN_STRING_BYTES_H_ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/package.json b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/package.json deleted file mode 100755 index 732b0dd1..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/node_modules/nan/package.json +++ /dev/null @@ -1,90 +0,0 @@ -{ - "name": "nan", - "version": "1.7.0", - "description": "Native Abstractions for Node.js: C++ header for Node 0.8->0.12 compatibility", - "main": "include_dirs.js", - "repository": { - "type": "git", - "url": "git://github.com/rvagg/nan.git" - }, - "scripts": { - "test": "tap --gc test/js/*-test.js", - "rebuild-tests": "pangyp rebuild --directory test" - }, - "contributors": [ - { - "name": "Rod Vagg", - "email": "r@va.gg", - "url": "https://github.com/rvagg" - }, - { - "name": "Benjamin Byholm", - "email": "bbyholm@abo.fi", - "url": "https://github.com/kkoopa/" - }, - { - "name": "Trevor Norris", - "email": "trev.norris@gmail.com", - "url": "https://github.com/trevnorris" - }, - { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "https://github.com/TooTallNate" - }, - { - "name": "Brett Lawson", - "email": "brett19@gmail.com", - "url": "https://github.com/brett19" - }, - { - "name": "Ben Noordhuis", - "email": "info@bnoordhuis.nl", - "url": "https://github.com/bnoordhuis" - }, - { - "name": "David Siegel", - "email": "david@artcom.de", - "url": "https://github.com/agnat" - } - ], - "devDependencies": { - "bindings": "~1.2.1", - "node-gyp": "~1.0.2", - "pangyp": "~2.0.1", - "tap": "~0.5.0", - "xtend": "~4.0.0" - }, - "license": "MIT", - "gitHead": "550efb5dde5cb6bf79db87ab48dce850e56e971a", - "bugs": { - "url": "https://github.com/rvagg/nan/issues" - }, - "homepage": "https://github.com/rvagg/nan", - "_id": "nan@1.7.0", - "_shasum": "755b997404e83cbe7bc08bc3c5c56291bce87438", - "_from": "nan@1.7.0", - "_npmVersion": "2.5.1", - "_nodeVersion": "0.12.0", - "_npmUser": { - "name": "kkoopa", - "email": "bbyholm@abo.fi" - }, - "maintainers": [ - { - "name": "rvagg", - "email": "rod@vagg.org" - }, - { - "name": "kkoopa", - "email": "bbyholm@abo.fi" - } - ], - "dist": { - "shasum": "755b997404e83cbe7bc08bc3c5c56291bce87438", - "tarball": "http://registry.npmjs.org/nan/-/nan-1.7.0.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/nan/-/nan-1.7.0.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/package.json b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/package.json deleted file mode 100755 index 52e0fec0..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/package.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "version": "0.2.21", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "contributors": [], - "repository": { - "type": "git", - "url": "git://github.com/mongodb/js-bson.git" - }, - "bugs": { - "url": "https://github.com/mongodb/js-bson/issues" - }, - "dependencies": { - "nan": "1.7.0" - }, - "devDependencies": { - "nodeunit": "0.9.0", - "gleak": "0.2.3", - "one": "2.X.X" - }, - "config": { - "native": false - }, - "main": "./lib/bson/index", - "directories": { - "lib": "./lib/bson" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "nodeunit ./test/node && TEST_NATIVE=TRUE nodeunit ./test/node" - }, - "browser": "lib/bson/bson.js", - "licenses": [ - { - "type": "Apache License, Version 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0" - } - ], - "gitHead": "a4b8ff14e3dcc92d144817a806f4c5ba536a7f2e", - "homepage": "https://github.com/mongodb/js-bson", - "_id": "bson@0.2.21", - "_shasum": "3755a5de71ac43f0e9a85f699c84d1ab73b0fcb3", - "_from": "bson@~0.2", - "_npmVersion": "2.7.1", - "_nodeVersion": "1.6.1", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "maintainers": [ - { - "name": "octave", - "email": "chinsay@gmail.com" - }, - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "3755a5de71ac43f0e9a85f699c84d1ab73b0fcb3", - "tarball": "http://registry.npmjs.org/bson/-/bson-0.2.21.tgz" - }, - "_resolved": "https://registry.npmjs.org/bson/-/bson-0.2.21.tgz" -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/gleak.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/gleak.js deleted file mode 100755 index c707cfcb..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/gleak.js +++ /dev/null @@ -1,21 +0,0 @@ - -var gleak = require('gleak')(); -gleak.ignore('AssertionError'); -gleak.ignore('testFullSpec_param_found'); -gleak.ignore('events'); -gleak.ignore('Uint8Array'); -gleak.ignore('Uint8ClampedArray'); -gleak.ignore('TAP_Global_Harness'); -gleak.ignore('setImmediate'); -gleak.ignore('clearImmediate'); - -gleak.ignore('DTRACE_NET_SERVER_CONNECTION'); -gleak.ignore('DTRACE_NET_STREAM_END'); -gleak.ignore('DTRACE_NET_SOCKET_READ'); -gleak.ignore('DTRACE_NET_SOCKET_WRITE'); -gleak.ignore('DTRACE_HTTP_SERVER_REQUEST'); -gleak.ignore('DTRACE_HTTP_SERVER_RESPONSE'); -gleak.ignore('DTRACE_HTTP_CLIENT_REQUEST'); -gleak.ignore('DTRACE_HTTP_CLIENT_RESPONSE'); - -module.exports = gleak; diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE deleted file mode 100755 index 7c435baa..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008-2011 Pivotal Labs - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js deleted file mode 100755 index 73834010..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js +++ /dev/null @@ -1,190 +0,0 @@ -jasmine.TrivialReporter = function(doc) { - this.document = doc || document; - this.suiteDivs = {}; - this.logRunningSpecs = false; -}; - -jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { - var el = document.createElement(type); - - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - - if (typeof child === 'string') { - el.appendChild(document.createTextNode(child)); - } else { - if (child) { el.appendChild(child); } - } - } - - for (var attr in attrs) { - if (attr == "className") { - el[attr] = attrs[attr]; - } else { - el.setAttribute(attr, attrs[attr]); - } - } - - return el; -}; - -jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { - var showPassed, showSkipped; - - this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' }, - this.createDom('div', { className: 'banner' }, - this.createDom('div', { className: 'logo' }, - this.createDom('span', { className: 'title' }, "Jasmine"), - this.createDom('span', { className: 'version' }, runner.env.versionString())), - this.createDom('div', { className: 'options' }, - "Show ", - showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), - showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") - ) - ), - - this.runnerDiv = this.createDom('div', { className: 'runner running' }, - this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), - this.runnerMessageSpan = this.createDom('span', {}, "Running..."), - this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) - ); - - this.document.body.appendChild(this.outerDiv); - - var suites = runner.suites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - var suiteDiv = this.createDom('div', { className: 'suite' }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), - this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); - this.suiteDivs[suite.id] = suiteDiv; - var parentDiv = this.outerDiv; - if (suite.parentSuite) { - parentDiv = this.suiteDivs[suite.parentSuite.id]; - } - parentDiv.appendChild(suiteDiv); - } - - this.startedAt = new Date(); - - var self = this; - showPassed.onclick = function(evt) { - if (showPassed.checked) { - self.outerDiv.className += ' show-passed'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); - } - }; - - showSkipped.onclick = function(evt) { - if (showSkipped.checked) { - self.outerDiv.className += ' show-skipped'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); - } - }; -}; - -jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { - var results = runner.results(); - var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; - this.runnerDiv.setAttribute("class", className); - //do it twice for IE - this.runnerDiv.setAttribute("className", className); - var specs = runner.specs(); - var specCount = 0; - for (var i = 0; i < specs.length; i++) { - if (this.specFilter(specs[i])) { - specCount++; - } - } - var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); - message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; - this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); - - this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); -}; - -jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { - var results = suite.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.totalCount === 0) { // todo: change this to check results.skipped - status = 'skipped'; - } - this.suiteDivs[suite.id].className += " " + status; -}; - -jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { - if (this.logRunningSpecs) { - this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); - } -}; - -jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { - var results = spec.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.skipped) { - status = 'skipped'; - } - var specDiv = this.createDom('div', { className: 'spec ' + status }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), - this.createDom('a', { - className: 'description', - href: '?spec=' + encodeURIComponent(spec.getFullName()), - title: spec.getFullName() - }, spec.description)); - - - var resultItems = results.getItems(); - var messagesDiv = this.createDom('div', { className: 'messages' }); - for (var i = 0; i < resultItems.length; i++) { - var result = resultItems[i]; - - if (result.type == 'log') { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); - } else if (result.type == 'expect' && result.passed && !result.passed()) { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); - - if (result.trace.stack) { - messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); - } - } - } - - if (messagesDiv.childNodes.length > 0) { - specDiv.appendChild(messagesDiv); - } - - this.suiteDivs[spec.suite.id].appendChild(specDiv); -}; - -jasmine.TrivialReporter.prototype.log = function() { - var console = jasmine.getGlobal().console; - if (console && console.log) { - if (console.log.apply) { - console.log.apply(console, arguments); - } else { - console.log(arguments); // ie fix: console.log.apply doesn't exist on ie - } - } -}; - -jasmine.TrivialReporter.prototype.getLocation = function() { - return this.document.location; -}; - -jasmine.TrivialReporter.prototype.specFilter = function(spec) { - var paramMap = {}; - var params = this.getLocation().search.substring(1).split('&'); - for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); - } - - if (!paramMap.spec) { - return true; - } - return spec.getFullName().indexOf(paramMap.spec) === 0; -}; diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css deleted file mode 100755 index 6583fe7c..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css +++ /dev/null @@ -1,166 +0,0 @@ -body { - font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; -} - - -.jasmine_reporter a:visited, .jasmine_reporter a { - color: #303; -} - -.jasmine_reporter a:hover, .jasmine_reporter a:active { - color: blue; -} - -.run_spec { - float:right; - padding-right: 5px; - font-size: .8em; - text-decoration: none; -} - -.jasmine_reporter { - margin: 0 5px; -} - -.banner { - color: #303; - background-color: #fef; - padding: 5px; -} - -.logo { - float: left; - font-size: 1.1em; - padding-left: 5px; -} - -.logo .version { - font-size: .6em; - padding-left: 1em; -} - -.runner.running { - background-color: yellow; -} - - -.options { - text-align: right; - font-size: .8em; -} - - - - -.suite { - border: 1px outset gray; - margin: 5px 0; - padding-left: 1em; -} - -.suite .suite { - margin: 5px; -} - -.suite.passed { - background-color: #dfd; -} - -.suite.failed { - background-color: #fdd; -} - -.spec { - margin: 5px; - padding-left: 1em; - clear: both; -} - -.spec.failed, .spec.passed, .spec.skipped { - padding-bottom: 5px; - border: 1px solid gray; -} - -.spec.failed { - background-color: #fbb; - border-color: red; -} - -.spec.passed { - background-color: #bfb; - border-color: green; -} - -.spec.skipped { - background-color: #bbb; -} - -.messages { - border-left: 1px dashed gray; - padding-left: 1em; - padding-right: 1em; -} - -.passed { - background-color: #cfc; - display: none; -} - -.failed { - background-color: #fbb; -} - -.skipped { - color: #777; - background-color: #eee; - display: none; -} - - -/*.resultMessage {*/ - /*white-space: pre;*/ -/*}*/ - -.resultMessage span.result { - display: block; - line-height: 2em; - color: black; -} - -.resultMessage .mismatch { - color: black; -} - -.stackTrace { - white-space: pre; - font-size: .8em; - margin-left: 10px; - max-height: 5em; - overflow: auto; - border: 1px inset red; - padding: 1em; - background: #eef; -} - -.finished-at { - padding-left: 1em; - font-size: .6em; -} - -.show-passed .passed, -.show-skipped .skipped { - display: block; -} - - -#jasmine_content { - position:fixed; - right: 100%; -} - -.runner { - border: 1px solid gray; - display: block; - margin: 5px 0; - padding: 2px 0 2px 10px; -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js deleted file mode 100755 index c3d2dc7d..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js +++ /dev/null @@ -1,2476 +0,0 @@ -var isCommonJS = typeof window == "undefined"; - -/** - * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework. - * - * @namespace - */ -var jasmine = {}; -if (isCommonJS) exports.jasmine = jasmine; -/** - * @private - */ -jasmine.unimplementedMethod_ = function() { - throw new Error("unimplemented method"); -}; - -/** - * Use jasmine.undefined instead of undefined, since undefined is just - * a plain old variable and may be redefined by somebody else. - * - * @private - */ -jasmine.undefined = jasmine.___undefined___; - -/** - * Show diagnostic messages in the console if set to true - * - */ -jasmine.VERBOSE = false; - -/** - * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed. - * - */ -jasmine.DEFAULT_UPDATE_INTERVAL = 250; - -/** - * Default timeout interval in milliseconds for waitsFor() blocks. - */ -jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; - -jasmine.getGlobal = function() { - function getGlobal() { - return this; - } - - return getGlobal(); -}; - -/** - * Allows for bound functions to be compared. Internal use only. - * - * @ignore - * @private - * @param base {Object} bound 'this' for the function - * @param name {Function} function to find - */ -jasmine.bindOriginal_ = function(base, name) { - var original = base[name]; - if (original.apply) { - return function() { - return original.apply(base, arguments); - }; - } else { - // IE support - return jasmine.getGlobal()[name]; - } -}; - -jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout'); -jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout'); -jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval'); -jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval'); - -jasmine.MessageResult = function(values) { - this.type = 'log'; - this.values = values; - this.trace = new Error(); // todo: test better -}; - -jasmine.MessageResult.prototype.toString = function() { - var text = ""; - for (var i = 0; i < this.values.length; i++) { - if (i > 0) text += " "; - if (jasmine.isString_(this.values[i])) { - text += this.values[i]; - } else { - text += jasmine.pp(this.values[i]); - } - } - return text; -}; - -jasmine.ExpectationResult = function(params) { - this.type = 'expect'; - this.matcherName = params.matcherName; - this.passed_ = params.passed; - this.expected = params.expected; - this.actual = params.actual; - this.message = this.passed_ ? 'Passed.' : params.message; - - var trace = (params.trace || new Error(this.message)); - this.trace = this.passed_ ? '' : trace; -}; - -jasmine.ExpectationResult.prototype.toString = function () { - return this.message; -}; - -jasmine.ExpectationResult.prototype.passed = function () { - return this.passed_; -}; - -/** - * Getter for the Jasmine environment. Ensures one gets created - */ -jasmine.getEnv = function() { - var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env(); - return env; -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isArray_ = function(value) { - return jasmine.isA_("Array", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isString_ = function(value) { - return jasmine.isA_("String", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isNumber_ = function(value) { - return jasmine.isA_("Number", value); -}; - -/** - * @ignore - * @private - * @param {String} typeName - * @param value - * @returns {Boolean} - */ -jasmine.isA_ = function(typeName, value) { - return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; -}; - -/** - * Pretty printer for expecations. Takes any object and turns it into a human-readable string. - * - * @param value {Object} an object to be outputted - * @returns {String} - */ -jasmine.pp = function(value) { - var stringPrettyPrinter = new jasmine.StringPrettyPrinter(); - stringPrettyPrinter.format(value); - return stringPrettyPrinter.string; -}; - -/** - * Returns true if the object is a DOM Node. - * - * @param {Object} obj object to check - * @returns {Boolean} - */ -jasmine.isDomNode = function(obj) { - return obj.nodeType > 0; -}; - -/** - * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter. - * - * @example - * // don't care about which function is passed in, as long as it's a function - * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function)); - * - * @param {Class} clazz - * @returns matchable object of the type clazz - */ -jasmine.any = function(clazz) { - return new jasmine.Matchers.Any(clazz); -}; - -/** - * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. - * - * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine - * expectation syntax. Spies can be checked if they were called or not and what the calling params were. - * - * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs). - * - * Spies are torn down at the end of every spec. - * - * Note: Do not call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj. - * - * @example - * // a stub - * var myStub = jasmine.createSpy('myStub'); // can be used anywhere - * - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // actual foo.not will not be called, execution stops - * spyOn(foo, 'not'); - - // foo.not spied upon, execution will continue to implementation - * spyOn(foo, 'not').andCallThrough(); - * - * // fake example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // foo.not(val) will return val - * spyOn(foo, 'not').andCallFake(function(value) {return value;}); - * - * // mock example - * foo.not(7 == 7); - * expect(foo.not).toHaveBeenCalled(); - * expect(foo.not).toHaveBeenCalledWith(true); - * - * @constructor - * @see spyOn, jasmine.createSpy, jasmine.createSpyObj - * @param {String} name - */ -jasmine.Spy = function(name) { - /** - * The name of the spy, if provided. - */ - this.identity = name || 'unknown'; - /** - * Is this Object a spy? - */ - this.isSpy = true; - /** - * The actual function this spy stubs. - */ - this.plan = function() { - }; - /** - * Tracking of the most recent call to the spy. - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy.mostRecentCall.args = [1, 2]; - */ - this.mostRecentCall = {}; - - /** - * Holds arguments for each call to the spy, indexed by call count - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy(7, 8); - * mySpy.mostRecentCall.args = [7, 8]; - * mySpy.argsForCall[0] = [1, 2]; - * mySpy.argsForCall[1] = [7, 8]; - */ - this.argsForCall = []; - this.calls = []; -}; - -/** - * Tells a spy to call through to the actual implemenatation. - * - * @example - * var foo = { - * bar: function() { // do some stuff } - * } - * - * // defining a spy on an existing property: foo.bar - * spyOn(foo, 'bar').andCallThrough(); - */ -jasmine.Spy.prototype.andCallThrough = function() { - this.plan = this.originalValue; - return this; -}; - -/** - * For setting the return value of a spy. - * - * @example - * // defining a spy from scratch: foo() returns 'baz' - * var foo = jasmine.createSpy('spy on foo').andReturn('baz'); - * - * // defining a spy on an existing property: foo.bar() returns 'baz' - * spyOn(foo, 'bar').andReturn('baz'); - * - * @param {Object} value - */ -jasmine.Spy.prototype.andReturn = function(value) { - this.plan = function() { - return value; - }; - return this; -}; - -/** - * For throwing an exception when a spy is called. - * - * @example - * // defining a spy from scratch: foo() throws an exception w/ message 'ouch' - * var foo = jasmine.createSpy('spy on foo').andThrow('baz'); - * - * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch' - * spyOn(foo, 'bar').andThrow('baz'); - * - * @param {String} exceptionMsg - */ -jasmine.Spy.prototype.andThrow = function(exceptionMsg) { - this.plan = function() { - throw exceptionMsg; - }; - return this; -}; - -/** - * Calls an alternate implementation when a spy is called. - * - * @example - * var baz = function() { - * // do some stuff, return something - * } - * // defining a spy from scratch: foo() calls the function baz - * var foo = jasmine.createSpy('spy on foo').andCall(baz); - * - * // defining a spy on an existing property: foo.bar() calls an anonymnous function - * spyOn(foo, 'bar').andCall(function() { return 'baz';} ); - * - * @param {Function} fakeFunc - */ -jasmine.Spy.prototype.andCallFake = function(fakeFunc) { - this.plan = fakeFunc; - return this; -}; - -/** - * Resets all of a spy's the tracking variables so that it can be used again. - * - * @example - * spyOn(foo, 'bar'); - * - * foo.bar(); - * - * expect(foo.bar.callCount).toEqual(1); - * - * foo.bar.reset(); - * - * expect(foo.bar.callCount).toEqual(0); - */ -jasmine.Spy.prototype.reset = function() { - this.wasCalled = false; - this.callCount = 0; - this.argsForCall = []; - this.calls = []; - this.mostRecentCall = {}; -}; - -jasmine.createSpy = function(name) { - - var spyObj = function() { - spyObj.wasCalled = true; - spyObj.callCount++; - var args = jasmine.util.argsToArray(arguments); - spyObj.mostRecentCall.object = this; - spyObj.mostRecentCall.args = args; - spyObj.argsForCall.push(args); - spyObj.calls.push({object: this, args: args}); - return spyObj.plan.apply(this, arguments); - }; - - var spy = new jasmine.Spy(name); - - for (var prop in spy) { - spyObj[prop] = spy[prop]; - } - - spyObj.reset(); - - return spyObj; -}; - -/** - * Determines whether an object is a spy. - * - * @param {jasmine.Spy|Object} putativeSpy - * @returns {Boolean} - */ -jasmine.isSpy = function(putativeSpy) { - return putativeSpy && putativeSpy.isSpy; -}; - -/** - * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something - * large in one call. - * - * @param {String} baseName name of spy class - * @param {Array} methodNames array of names of methods to make spies - */ -jasmine.createSpyObj = function(baseName, methodNames) { - if (!jasmine.isArray_(methodNames) || methodNames.length === 0) { - throw new Error('createSpyObj requires a non-empty array of method names to create spies for'); - } - var obj = {}; - for (var i = 0; i < methodNames.length; i++) { - obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]); - } - return obj; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the current spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.log = function() { - var spec = jasmine.getEnv().currentSpec; - spec.log.apply(spec, arguments); -}; - -/** - * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy. - * - * @example - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops - * - * @see jasmine.createSpy - * @param obj - * @param methodName - * @returns a Jasmine spy that can be chained with all spy methods - */ -var spyOn = function(obj, methodName) { - return jasmine.getEnv().currentSpec.spyOn(obj, methodName); -}; -if (isCommonJS) exports.spyOn = spyOn; - -/** - * Creates a Jasmine spec that will be added to the current suite. - * - * // TODO: pending tests - * - * @example - * it('should be true', function() { - * expect(true).toEqual(true); - * }); - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var it = function(desc, func) { - return jasmine.getEnv().it(desc, func); -}; -if (isCommonJS) exports.it = it; - -/** - * Creates a disabled Jasmine spec. - * - * A convenience method that allows existing specs to be disabled temporarily during development. - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var xit = function(desc, func) { - return jasmine.getEnv().xit(desc, func); -}; -if (isCommonJS) exports.xit = xit; - -/** - * Starts a chain for a Jasmine expectation. - * - * It is passed an Object that is the actual value and should chain to one of the many - * jasmine.Matchers functions. - * - * @param {Object} actual Actual value to test against and expected value - */ -var expect = function(actual) { - return jasmine.getEnv().currentSpec.expect(actual); -}; -if (isCommonJS) exports.expect = expect; - -/** - * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs. - * - * @param {Function} func Function that defines part of a jasmine spec. - */ -var runs = function(func) { - jasmine.getEnv().currentSpec.runs(func); -}; -if (isCommonJS) exports.runs = runs; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -var waits = function(timeout) { - jasmine.getEnv().currentSpec.waits(timeout); -}; -if (isCommonJS) exports.waits = waits; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); -}; -if (isCommonJS) exports.waitsFor = waitsFor; - -/** - * A function that is called before each spec in a suite. - * - * Used for spec setup, including validating assumptions. - * - * @param {Function} beforeEachFunction - */ -var beforeEach = function(beforeEachFunction) { - jasmine.getEnv().beforeEach(beforeEachFunction); -}; -if (isCommonJS) exports.beforeEach = beforeEach; - -/** - * A function that is called after each spec in a suite. - * - * Used for restoring any state that is hijacked during spec execution. - * - * @param {Function} afterEachFunction - */ -var afterEach = function(afterEachFunction) { - jasmine.getEnv().afterEach(afterEachFunction); -}; -if (isCommonJS) exports.afterEach = afterEach; - -/** - * Defines a suite of specifications. - * - * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared - * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization - * of setup in some tests. - * - * @example - * // TODO: a simple suite - * - * // TODO: a simple suite with a nested describe block - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var describe = function(description, specDefinitions) { - return jasmine.getEnv().describe(description, specDefinitions); -}; -if (isCommonJS) exports.describe = describe; - -/** - * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development. - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var xdescribe = function(description, specDefinitions) { - return jasmine.getEnv().xdescribe(description, specDefinitions); -}; -if (isCommonJS) exports.xdescribe = xdescribe; - - -// Provide the XMLHttpRequest class for IE 5.x-6.x: -jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() { - function tryIt(f) { - try { - return f(); - } catch(e) { - } - return null; - } - - var xhr = tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.6.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.3.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP"); - }) || - tryIt(function() { - return new ActiveXObject("Microsoft.XMLHTTP"); - }); - - if (!xhr) throw new Error("This browser does not support XMLHttpRequest."); - - return xhr; -} : XMLHttpRequest; -/** - * @namespace - */ -jasmine.util = {}; - -/** - * Declare that a child class inherit it's prototype from the parent class. - * - * @private - * @param {Function} childClass - * @param {Function} parentClass - */ -jasmine.util.inherit = function(childClass, parentClass) { - /** - * @private - */ - var subclass = function() { - }; - subclass.prototype = parentClass.prototype; - childClass.prototype = new subclass(); -}; - -jasmine.util.formatException = function(e) { - var lineNumber; - if (e.line) { - lineNumber = e.line; - } - else if (e.lineNumber) { - lineNumber = e.lineNumber; - } - - var file; - - if (e.sourceURL) { - file = e.sourceURL; - } - else if (e.fileName) { - file = e.fileName; - } - - var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString(); - - if (file && lineNumber) { - message += ' in ' + file + ' (line ' + lineNumber + ')'; - } - - return message; -}; - -jasmine.util.htmlEscape = function(str) { - if (!str) return str; - return str.replace(/&/g, '&') - .replace(//g, '>'); -}; - -jasmine.util.argsToArray = function(args) { - var arrayOfArgs = []; - for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]); - return arrayOfArgs; -}; - -jasmine.util.extend = function(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; -}; - -/** - * Environment for Jasmine - * - * @constructor - */ -jasmine.Env = function() { - this.currentSpec = null; - this.currentSuite = null; - this.currentRunner_ = new jasmine.Runner(this); - - this.reporter = new jasmine.MultiReporter(); - - this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; - this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; - this.lastUpdate = 0; - this.specFilter = function() { - return true; - }; - - this.nextSpecId_ = 0; - this.nextSuiteId_ = 0; - this.equalityTesters_ = []; - - // wrap matchers - this.matchersClass = function() { - jasmine.Matchers.apply(this, arguments); - }; - jasmine.util.inherit(this.matchersClass, jasmine.Matchers); - - jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); -}; - - -jasmine.Env.prototype.setTimeout = jasmine.setTimeout; -jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; -jasmine.Env.prototype.setInterval = jasmine.setInterval; -jasmine.Env.prototype.clearInterval = jasmine.clearInterval; - -/** - * @returns an object containing jasmine version build info, if set. - */ -jasmine.Env.prototype.version = function () { - if (jasmine.version_) { - return jasmine.version_; - } else { - throw new Error('Version not set'); - } -}; - -/** - * @returns string containing jasmine version build info, if set. - */ -jasmine.Env.prototype.versionString = function() { - if (!jasmine.version_) { - return "version unknown"; - } - - var version = this.version(); - var versionString = version.major + "." + version.minor + "." + version.build; - if (version.release_candidate) { - versionString += ".rc" + version.release_candidate; - } - versionString += " revision " + version.revision; - return versionString; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSpecId = function () { - return this.nextSpecId_++; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSuiteId = function () { - return this.nextSuiteId_++; -}; - -/** - * Register a reporter to receive status updates from Jasmine. - * @param {jasmine.Reporter} reporter An object which will receive status updates. - */ -jasmine.Env.prototype.addReporter = function(reporter) { - this.reporter.addReporter(reporter); -}; - -jasmine.Env.prototype.execute = function() { - this.currentRunner_.execute(); -}; - -jasmine.Env.prototype.describe = function(description, specDefinitions) { - var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); - - var parentSuite = this.currentSuite; - if (parentSuite) { - parentSuite.add(suite); - } else { - this.currentRunner_.add(suite); - } - - this.currentSuite = suite; - - var declarationError = null; - try { - specDefinitions.call(suite); - } catch(e) { - declarationError = e; - } - - if (declarationError) { - this.it("encountered a declaration exception", function() { - throw declarationError; - }); - } - - this.currentSuite = parentSuite; - - return suite; -}; - -jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { - if (this.currentSuite) { - this.currentSuite.beforeEach(beforeEachFunction); - } else { - this.currentRunner_.beforeEach(beforeEachFunction); - } -}; - -jasmine.Env.prototype.currentRunner = function () { - return this.currentRunner_; -}; - -jasmine.Env.prototype.afterEach = function(afterEachFunction) { - if (this.currentSuite) { - this.currentSuite.afterEach(afterEachFunction); - } else { - this.currentRunner_.afterEach(afterEachFunction); - } - -}; - -jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { - return { - execute: function() { - } - }; -}; - -jasmine.Env.prototype.it = function(description, func) { - var spec = new jasmine.Spec(this, this.currentSuite, description); - this.currentSuite.add(spec); - this.currentSpec = spec; - - if (func) { - spec.runs(func); - } - - return spec; -}; - -jasmine.Env.prototype.xit = function(desc, func) { - return { - id: this.nextSpecId(), - runs: function() { - } - }; -}; - -jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { - if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { - return true; - } - - a.__Jasmine_been_here_before__ = b; - b.__Jasmine_been_here_before__ = a; - - var hasKey = function(obj, keyName) { - return obj !== null && obj[keyName] !== jasmine.undefined; - }; - - for (var property in b) { - if (!hasKey(a, property) && hasKey(b, property)) { - mismatchKeys.push("expected has key '" + property + "', but missing from actual."); - } - } - for (property in a) { - if (!hasKey(b, property) && hasKey(a, property)) { - mismatchKeys.push("expected missing key '" + property + "', but present in actual."); - } - } - for (property in b) { - if (property == '__Jasmine_been_here_before__') continue; - if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { - mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); - } - } - - if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { - mismatchValues.push("arrays were not the same length"); - } - - delete a.__Jasmine_been_here_before__; - delete b.__Jasmine_been_here_before__; - return (mismatchKeys.length === 0 && mismatchValues.length === 0); -}; - -jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { - mismatchKeys = mismatchKeys || []; - mismatchValues = mismatchValues || []; - - for (var i = 0; i < this.equalityTesters_.length; i++) { - var equalityTester = this.equalityTesters_[i]; - var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); - if (result !== jasmine.undefined) return result; - } - - if (a === b) return true; - - if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { - return (a == jasmine.undefined && b == jasmine.undefined); - } - - if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { - return a === b; - } - - if (a instanceof Date && b instanceof Date) { - return a.getTime() == b.getTime(); - } - - if (a instanceof jasmine.Matchers.Any) { - return a.matches(b); - } - - if (b instanceof jasmine.Matchers.Any) { - return b.matches(a); - } - - if (jasmine.isString_(a) && jasmine.isString_(b)) { - return (a == b); - } - - if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { - return (a == b); - } - - if (typeof a === "object" && typeof b === "object") { - return this.compareObjects_(a, b, mismatchKeys, mismatchValues); - } - - //Straight check - return (a === b); -}; - -jasmine.Env.prototype.contains_ = function(haystack, needle) { - if (jasmine.isArray_(haystack)) { - for (var i = 0; i < haystack.length; i++) { - if (this.equals_(haystack[i], needle)) return true; - } - return false; - } - return haystack.indexOf(needle) >= 0; -}; - -jasmine.Env.prototype.addEqualityTester = function(equalityTester) { - this.equalityTesters_.push(equalityTester); -}; -/** No-op base class for Jasmine reporters. - * - * @constructor - */ -jasmine.Reporter = function() { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerStarting = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerResults = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecStarting = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecResults = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.log = function(str) { -}; - -/** - * Blocks are functions with executable code that make up a spec. - * - * @constructor - * @param {jasmine.Env} env - * @param {Function} func - * @param {jasmine.Spec} spec - */ -jasmine.Block = function(env, func, spec) { - this.env = env; - this.func = func; - this.spec = spec; -}; - -jasmine.Block.prototype.execute = function(onComplete) { - try { - this.func.apply(this.spec); - } catch (e) { - this.spec.fail(e); - } - onComplete(); -}; -/** JavaScript API reporter. - * - * @constructor - */ -jasmine.JsApiReporter = function() { - this.started = false; - this.finished = false; - this.suites_ = []; - this.results_ = {}; -}; - -jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) { - this.started = true; - var suites = runner.topLevelSuites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - this.suites_.push(this.summarize_(suite)); - } -}; - -jasmine.JsApiReporter.prototype.suites = function() { - return this.suites_; -}; - -jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) { - var isSuite = suiteOrSpec instanceof jasmine.Suite; - var summary = { - id: suiteOrSpec.id, - name: suiteOrSpec.description, - type: isSuite ? 'suite' : 'spec', - children: [] - }; - - if (isSuite) { - var children = suiteOrSpec.children(); - for (var i = 0; i < children.length; i++) { - summary.children.push(this.summarize_(children[i])); - } - } - return summary; -}; - -jasmine.JsApiReporter.prototype.results = function() { - return this.results_; -}; - -jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) { - return this.results_[specId]; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) { - this.finished = true; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) { - this.results_[spec.id] = { - messages: spec.results().getItems(), - result: spec.results().failedCount > 0 ? "failed" : "passed" - }; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.log = function(str) { -}; - -jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){ - var results = {}; - for (var i = 0; i < specIds.length; i++) { - var specId = specIds[i]; - results[specId] = this.summarizeResult_(this.results_[specId]); - } - return results; -}; - -jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ - var summaryMessages = []; - var messagesLength = result.messages.length; - for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) { - var resultMessage = result.messages[messageIndex]; - summaryMessages.push({ - text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined, - passed: resultMessage.passed ? resultMessage.passed() : true, - type: resultMessage.type, - message: resultMessage.message, - trace: { - stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined - } - }); - } - - return { - result : result.result, - messages : summaryMessages - }; -}; - -/** - * @constructor - * @param {jasmine.Env} env - * @param actual - * @param {jasmine.Spec} spec - */ -jasmine.Matchers = function(env, actual, spec, opt_isNot) { - this.env = env; - this.actual = actual; - this.spec = spec; - this.isNot = opt_isNot || false; - this.reportWasCalled_ = false; -}; - -// todo: @deprecated as of Jasmine 0.11, remove soon [xw] -jasmine.Matchers.pp = function(str) { - throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!"); -}; - -// todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw] -jasmine.Matchers.prototype.report = function(result, failing_message, details) { - throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs"); -}; - -jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) { - for (var methodName in prototype) { - if (methodName == 'report') continue; - var orig = prototype[methodName]; - matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig); - } -}; - -jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { - return function() { - var matcherArgs = jasmine.util.argsToArray(arguments); - var result = matcherFunction.apply(this, arguments); - - if (this.isNot) { - result = !result; - } - - if (this.reportWasCalled_) return result; - - var message; - if (!result) { - if (this.message) { - message = this.message.apply(this, arguments); - if (jasmine.isArray_(message)) { - message = message[this.isNot ? 1 : 0]; - } - } else { - var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); - message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate; - if (matcherArgs.length > 0) { - for (var i = 0; i < matcherArgs.length; i++) { - if (i > 0) message += ","; - message += " " + jasmine.pp(matcherArgs[i]); - } - } - message += "."; - } - } - var expectationResult = new jasmine.ExpectationResult({ - matcherName: matcherName, - passed: result, - expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0], - actual: this.actual, - message: message - }); - this.spec.addMatcherResult(expectationResult); - return jasmine.undefined; - }; -}; - - - - -/** - * toBe: compares the actual to the expected using === - * @param expected - */ -jasmine.Matchers.prototype.toBe = function(expected) { - return this.actual === expected; -}; - -/** - * toNotBe: compares the actual to the expected using !== - * @param expected - * @deprecated as of 1.0. Use not.toBe() instead. - */ -jasmine.Matchers.prototype.toNotBe = function(expected) { - return this.actual !== expected; -}; - -/** - * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc. - * - * @param expected - */ -jasmine.Matchers.prototype.toEqual = function(expected) { - return this.env.equals_(this.actual, expected); -}; - -/** - * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual - * @param expected - * @deprecated as of 1.0. Use not.toNotEqual() instead. - */ -jasmine.Matchers.prototype.toNotEqual = function(expected) { - return !this.env.equals_(this.actual, expected); -}; - -/** - * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes - * a pattern or a String. - * - * @param expected - */ -jasmine.Matchers.prototype.toMatch = function(expected) { - return new RegExp(expected).test(this.actual); -}; - -/** - * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch - * @param expected - * @deprecated as of 1.0. Use not.toMatch() instead. - */ -jasmine.Matchers.prototype.toNotMatch = function(expected) { - return !(new RegExp(expected).test(this.actual)); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeDefined = function() { - return (this.actual !== jasmine.undefined); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeUndefined = function() { - return (this.actual === jasmine.undefined); -}; - -/** - * Matcher that compares the actual to null. - */ -jasmine.Matchers.prototype.toBeNull = function() { - return (this.actual === null); -}; - -/** - * Matcher that boolean not-nots the actual. - */ -jasmine.Matchers.prototype.toBeTruthy = function() { - return !!this.actual; -}; - - -/** - * Matcher that boolean nots the actual. - */ -jasmine.Matchers.prototype.toBeFalsy = function() { - return !this.actual; -}; - - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called. - */ -jasmine.Matchers.prototype.toHaveBeenCalled = function() { - if (arguments.length > 0) { - throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to have been called.", - "Expected spy " + this.actual.identity + " not to have been called." - ]; - }; - - return this.actual.wasCalled; -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalled() instead */ -jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was not called. - * - * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead - */ -jasmine.Matchers.prototype.wasNotCalled = function() { - if (arguments.length > 0) { - throw new Error('wasNotCalled does not take arguments'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to not have been called.", - "Expected spy " + this.actual.identity + " to have been called." - ]; - }; - - return !this.actual.wasCalled; -}; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters. - * - * @example - * - */ -jasmine.Matchers.prototype.toHaveBeenCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - this.message = function() { - if (this.actual.callCount === 0) { - // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw] - return [ - "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.", - "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was." - ]; - } else { - return [ - "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall), - "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall) - ]; - } - }; - - return this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith; - -/** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasNotCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was", - "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was" - ]; - }; - - return !this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** - * Matcher that checks that the expected item is an element in the actual Array. - * - * @param {Object} expected - */ -jasmine.Matchers.prototype.toContain = function(expected) { - return this.env.contains_(this.actual, expected); -}; - -/** - * Matcher that checks that the expected item is NOT an element in the actual Array. - * - * @param {Object} expected - * @deprecated as of 1.0. Use not.toNotContain() instead. - */ -jasmine.Matchers.prototype.toNotContain = function(expected) { - return !this.env.contains_(this.actual, expected); -}; - -jasmine.Matchers.prototype.toBeLessThan = function(expected) { - return this.actual < expected; -}; - -jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { - return this.actual > expected; -}; - -/** - * Matcher that checks that the expected item is equal to the actual item - * up to a given level of decimal precision (default 2). - * - * @param {Number} expected - * @param {Number} precision - */ -jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) { - if (!(precision === 0)) { - precision = precision || 2; - } - var multiplier = Math.pow(10, precision); - var actual = Math.round(this.actual * multiplier); - expected = Math.round(expected * multiplier); - return expected == actual; -}; - -/** - * Matcher that checks that the expected exception was thrown by the actual. - * - * @param {String} expected - */ -jasmine.Matchers.prototype.toThrow = function(expected) { - var result = false; - var exception; - if (typeof this.actual != 'function') { - throw new Error('Actual is not a function'); - } - try { - this.actual(); - } catch (e) { - exception = e; - } - if (exception) { - result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); - } - - var not = this.isNot ? "not " : ""; - - this.message = function() { - if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) { - return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' '); - } else { - return "Expected function to throw an exception."; - } - }; - - return result; -}; - -jasmine.Matchers.Any = function(expectedClass) { - this.expectedClass = expectedClass; -}; - -jasmine.Matchers.Any.prototype.matches = function(other) { - if (this.expectedClass == String) { - return typeof other == 'string' || other instanceof String; - } - - if (this.expectedClass == Number) { - return typeof other == 'number' || other instanceof Number; - } - - if (this.expectedClass == Function) { - return typeof other == 'function' || other instanceof Function; - } - - if (this.expectedClass == Object) { - return typeof other == 'object'; - } - - return other instanceof this.expectedClass; -}; - -jasmine.Matchers.Any.prototype.toString = function() { - return ''; -}; - -/** - * @constructor - */ -jasmine.MultiReporter = function() { - this.subReporters_ = []; -}; -jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter); - -jasmine.MultiReporter.prototype.addReporter = function(reporter) { - this.subReporters_.push(reporter); -}; - -(function() { - var functionNames = [ - "reportRunnerStarting", - "reportRunnerResults", - "reportSuiteResults", - "reportSpecStarting", - "reportSpecResults", - "log" - ]; - for (var i = 0; i < functionNames.length; i++) { - var functionName = functionNames[i]; - jasmine.MultiReporter.prototype[functionName] = (function(functionName) { - return function() { - for (var j = 0; j < this.subReporters_.length; j++) { - var subReporter = this.subReporters_[j]; - if (subReporter[functionName]) { - subReporter[functionName].apply(subReporter, arguments); - } - } - }; - })(functionName); - } -})(); -/** - * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults - * - * @constructor - */ -jasmine.NestedResults = function() { - /** - * The total count of results - */ - this.totalCount = 0; - /** - * Number of passed results - */ - this.passedCount = 0; - /** - * Number of failed results - */ - this.failedCount = 0; - /** - * Was this suite/spec skipped? - */ - this.skipped = false; - /** - * @ignore - */ - this.items_ = []; -}; - -/** - * Roll up the result counts. - * - * @param result - */ -jasmine.NestedResults.prototype.rollupCounts = function(result) { - this.totalCount += result.totalCount; - this.passedCount += result.passedCount; - this.failedCount += result.failedCount; -}; - -/** - * Adds a log message. - * @param values Array of message parts which will be concatenated later. - */ -jasmine.NestedResults.prototype.log = function(values) { - this.items_.push(new jasmine.MessageResult(values)); -}; - -/** - * Getter for the results: message & results. - */ -jasmine.NestedResults.prototype.getItems = function() { - return this.items_; -}; - -/** - * Adds a result, tracking counts (total, passed, & failed) - * @param {jasmine.ExpectationResult|jasmine.NestedResults} result - */ -jasmine.NestedResults.prototype.addResult = function(result) { - if (result.type != 'log') { - if (result.items_) { - this.rollupCounts(result); - } else { - this.totalCount++; - if (result.passed()) { - this.passedCount++; - } else { - this.failedCount++; - } - } - } - this.items_.push(result); -}; - -/** - * @returns {Boolean} True if everything below passed - */ -jasmine.NestedResults.prototype.passed = function() { - return this.passedCount === this.totalCount; -}; -/** - * Base class for pretty printing for expectation results. - */ -jasmine.PrettyPrinter = function() { - this.ppNestLevel_ = 0; -}; - -/** - * Formats a value in a nice, human-readable string. - * - * @param value - */ -jasmine.PrettyPrinter.prototype.format = function(value) { - if (this.ppNestLevel_ > 40) { - throw new Error('jasmine.PrettyPrinter: format() nested too deeply!'); - } - - this.ppNestLevel_++; - try { - if (value === jasmine.undefined) { - this.emitScalar('undefined'); - } else if (value === null) { - this.emitScalar('null'); - } else if (value === jasmine.getGlobal()) { - this.emitScalar(''); - } else if (value instanceof jasmine.Matchers.Any) { - this.emitScalar(value.toString()); - } else if (typeof value === 'string') { - this.emitString(value); - } else if (jasmine.isSpy(value)) { - this.emitScalar("spy on " + value.identity); - } else if (value instanceof RegExp) { - this.emitScalar(value.toString()); - } else if (typeof value === 'function') { - this.emitScalar('Function'); - } else if (typeof value.nodeType === 'number') { - this.emitScalar('HTMLNode'); - } else if (value instanceof Date) { - this.emitScalar('Date(' + value + ')'); - } else if (value.__Jasmine_been_here_before__) { - this.emitScalar(''); - } else if (jasmine.isArray_(value) || typeof value == 'object') { - value.__Jasmine_been_here_before__ = true; - if (jasmine.isArray_(value)) { - this.emitArray(value); - } else { - this.emitObject(value); - } - delete value.__Jasmine_been_here_before__; - } else { - this.emitScalar(value.toString()); - } - } finally { - this.ppNestLevel_--; - } -}; - -jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) { - for (var property in obj) { - if (property == '__Jasmine_been_here_before__') continue; - fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined && - obj.__lookupGetter__(property) !== null) : false); - } -}; - -jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_; - -jasmine.StringPrettyPrinter = function() { - jasmine.PrettyPrinter.call(this); - - this.string = ''; -}; -jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter); - -jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) { - this.append(value); -}; - -jasmine.StringPrettyPrinter.prototype.emitString = function(value) { - this.append("'" + value + "'"); -}; - -jasmine.StringPrettyPrinter.prototype.emitArray = function(array) { - this.append('[ '); - for (var i = 0; i < array.length; i++) { - if (i > 0) { - this.append(', '); - } - this.format(array[i]); - } - this.append(' ]'); -}; - -jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) { - var self = this; - this.append('{ '); - var first = true; - - this.iterateObject(obj, function(property, isGetter) { - if (first) { - first = false; - } else { - self.append(', '); - } - - self.append(property); - self.append(' : '); - if (isGetter) { - self.append(''); - } else { - self.format(obj[property]); - } - }); - - this.append(' }'); -}; - -jasmine.StringPrettyPrinter.prototype.append = function(value) { - this.string += value; -}; -jasmine.Queue = function(env) { - this.env = env; - this.blocks = []; - this.running = false; - this.index = 0; - this.offset = 0; - this.abort = false; -}; - -jasmine.Queue.prototype.addBefore = function(block) { - this.blocks.unshift(block); -}; - -jasmine.Queue.prototype.add = function(block) { - this.blocks.push(block); -}; - -jasmine.Queue.prototype.insertNext = function(block) { - this.blocks.splice((this.index + this.offset + 1), 0, block); - this.offset++; -}; - -jasmine.Queue.prototype.start = function(onComplete) { - this.running = true; - this.onComplete = onComplete; - this.next_(); -}; - -jasmine.Queue.prototype.isRunning = function() { - return this.running; -}; - -jasmine.Queue.LOOP_DONT_RECURSE = true; - -jasmine.Queue.prototype.next_ = function() { - var self = this; - var goAgain = true; - - while (goAgain) { - goAgain = false; - - if (self.index < self.blocks.length && !this.abort) { - var calledSynchronously = true; - var completedSynchronously = false; - - var onComplete = function () { - if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) { - completedSynchronously = true; - return; - } - - if (self.blocks[self.index].abort) { - self.abort = true; - } - - self.offset = 0; - self.index++; - - var now = new Date().getTime(); - if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) { - self.env.lastUpdate = now; - self.env.setTimeout(function() { - self.next_(); - }, 0); - } else { - if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) { - goAgain = true; - } else { - self.next_(); - } - } - }; - self.blocks[self.index].execute(onComplete); - - calledSynchronously = false; - if (completedSynchronously) { - onComplete(); - } - - } else { - self.running = false; - if (self.onComplete) { - self.onComplete(); - } - } - } -}; - -jasmine.Queue.prototype.results = function() { - var results = new jasmine.NestedResults(); - for (var i = 0; i < this.blocks.length; i++) { - if (this.blocks[i].results) { - results.addResult(this.blocks[i].results()); - } - } - return results; -}; - - -/** - * Runner - * - * @constructor - * @param {jasmine.Env} env - */ -jasmine.Runner = function(env) { - var self = this; - self.env = env; - self.queue = new jasmine.Queue(env); - self.before_ = []; - self.after_ = []; - self.suites_ = []; -}; - -jasmine.Runner.prototype.execute = function() { - var self = this; - if (self.env.reporter.reportRunnerStarting) { - self.env.reporter.reportRunnerStarting(this); - } - self.queue.start(function () { - self.finishCallback(); - }); -}; - -jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.splice(0,0,beforeEachFunction); -}; - -jasmine.Runner.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.splice(0,0,afterEachFunction); -}; - - -jasmine.Runner.prototype.finishCallback = function() { - this.env.reporter.reportRunnerResults(this); -}; - -jasmine.Runner.prototype.addSuite = function(suite) { - this.suites_.push(suite); -}; - -jasmine.Runner.prototype.add = function(block) { - if (block instanceof jasmine.Suite) { - this.addSuite(block); - } - this.queue.add(block); -}; - -jasmine.Runner.prototype.specs = function () { - var suites = this.suites(); - var specs = []; - for (var i = 0; i < suites.length; i++) { - specs = specs.concat(suites[i].specs()); - } - return specs; -}; - -jasmine.Runner.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Runner.prototype.topLevelSuites = function() { - var topLevelSuites = []; - for (var i = 0; i < this.suites_.length; i++) { - if (!this.suites_[i].parentSuite) { - topLevelSuites.push(this.suites_[i]); - } - } - return topLevelSuites; -}; - -jasmine.Runner.prototype.results = function() { - return this.queue.results(); -}; -/** - * Internal representation of a Jasmine specification, or test. - * - * @constructor - * @param {jasmine.Env} env - * @param {jasmine.Suite} suite - * @param {String} description - */ -jasmine.Spec = function(env, suite, description) { - if (!env) { - throw new Error('jasmine.Env() required'); - } - if (!suite) { - throw new Error('jasmine.Suite() required'); - } - var spec = this; - spec.id = env.nextSpecId ? env.nextSpecId() : null; - spec.env = env; - spec.suite = suite; - spec.description = description; - spec.queue = new jasmine.Queue(env); - - spec.afterCallbacks = []; - spec.spies_ = []; - - spec.results_ = new jasmine.NestedResults(); - spec.results_.description = description; - spec.matchersClass = null; -}; - -jasmine.Spec.prototype.getFullName = function() { - return this.suite.getFullName() + ' ' + this.description + '.'; -}; - - -jasmine.Spec.prototype.results = function() { - return this.results_; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.Spec.prototype.log = function() { - return this.results_.log(arguments); -}; - -jasmine.Spec.prototype.runs = function (func) { - var block = new jasmine.Block(this.env, func, this); - this.addToQueue(block); - return this; -}; - -jasmine.Spec.prototype.addToQueue = function (block) { - if (this.queue.isRunning()) { - this.queue.insertNext(block); - } else { - this.queue.add(block); - } -}; - -/** - * @param {jasmine.ExpectationResult} result - */ -jasmine.Spec.prototype.addMatcherResult = function(result) { - this.results_.addResult(result); -}; - -jasmine.Spec.prototype.expect = function(actual) { - var positive = new (this.getMatchersClass_())(this.env, actual, this); - positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); - return positive; -}; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -jasmine.Spec.prototype.waits = function(timeout) { - var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this); - this.addToQueue(waitsFunc); - return this; -}; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - var latchFunction_ = null; - var optional_timeoutMessage_ = null; - var optional_timeout_ = null; - - for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i]; - switch (typeof arg) { - case 'function': - latchFunction_ = arg; - break; - case 'string': - optional_timeoutMessage_ = arg; - break; - case 'number': - optional_timeout_ = arg; - break; - } - } - - var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this); - this.addToQueue(waitsForFunc); - return this; -}; - -jasmine.Spec.prototype.fail = function (e) { - var expectationResult = new jasmine.ExpectationResult({ - passed: false, - message: e ? jasmine.util.formatException(e) : 'Exception', - trace: { stack: e.stack } - }); - this.results_.addResult(expectationResult); -}; - -jasmine.Spec.prototype.getMatchersClass_ = function() { - return this.matchersClass || this.env.matchersClass; -}; - -jasmine.Spec.prototype.addMatchers = function(matchersPrototype) { - var parent = this.getMatchersClass_(); - var newMatchersClass = function() { - parent.apply(this, arguments); - }; - jasmine.util.inherit(newMatchersClass, parent); - jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass); - this.matchersClass = newMatchersClass; -}; - -jasmine.Spec.prototype.finishCallback = function() { - this.env.reporter.reportSpecResults(this); -}; - -jasmine.Spec.prototype.finish = function(onComplete) { - this.removeAllSpies(); - this.finishCallback(); - if (onComplete) { - onComplete(); - } -}; - -jasmine.Spec.prototype.after = function(doAfter) { - if (this.queue.isRunning()) { - this.queue.add(new jasmine.Block(this.env, doAfter, this)); - } else { - this.afterCallbacks.unshift(doAfter); - } -}; - -jasmine.Spec.prototype.execute = function(onComplete) { - var spec = this; - if (!spec.env.specFilter(spec)) { - spec.results_.skipped = true; - spec.finish(onComplete); - return; - } - - this.env.reporter.reportSpecStarting(this); - - spec.env.currentSpec = spec; - - spec.addBeforesAndAftersToQueue(); - - spec.queue.start(function () { - spec.finish(onComplete); - }); -}; - -jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() { - var runner = this.env.currentRunner(); - var i; - - for (var suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)); - } - } - for (i = 0; i < runner.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)); - } - for (i = 0; i < this.afterCallbacks.length; i++) { - this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this)); - } - for (suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, suite.after_[i], this)); - } - } - for (i = 0; i < runner.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, runner.after_[i], this)); - } -}; - -jasmine.Spec.prototype.explodes = function() { - throw 'explodes function should not have been called'; -}; - -jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) { - if (obj == jasmine.undefined) { - throw "spyOn could not find an object to spy upon for " + methodName + "()"; - } - - if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) { - throw methodName + '() method does not exist'; - } - - if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) { - throw new Error(methodName + ' has already been spied upon'); - } - - var spyObj = jasmine.createSpy(methodName); - - this.spies_.push(spyObj); - spyObj.baseObj = obj; - spyObj.methodName = methodName; - spyObj.originalValue = obj[methodName]; - - obj[methodName] = spyObj; - - return spyObj; -}; - -jasmine.Spec.prototype.removeAllSpies = function() { - for (var i = 0; i < this.spies_.length; i++) { - var spy = this.spies_[i]; - spy.baseObj[spy.methodName] = spy.originalValue; - } - this.spies_ = []; -}; - -/** - * Internal representation of a Jasmine suite. - * - * @constructor - * @param {jasmine.Env} env - * @param {String} description - * @param {Function} specDefinitions - * @param {jasmine.Suite} parentSuite - */ -jasmine.Suite = function(env, description, specDefinitions, parentSuite) { - var self = this; - self.id = env.nextSuiteId ? env.nextSuiteId() : null; - self.description = description; - self.queue = new jasmine.Queue(env); - self.parentSuite = parentSuite; - self.env = env; - self.before_ = []; - self.after_ = []; - self.children_ = []; - self.suites_ = []; - self.specs_ = []; -}; - -jasmine.Suite.prototype.getFullName = function() { - var fullName = this.description; - for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { - fullName = parentSuite.description + ' ' + fullName; - } - return fullName; -}; - -jasmine.Suite.prototype.finish = function(onComplete) { - this.env.reporter.reportSuiteResults(this); - this.finished = true; - if (typeof(onComplete) == 'function') { - onComplete(); - } -}; - -jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.unshift(beforeEachFunction); -}; - -jasmine.Suite.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.unshift(afterEachFunction); -}; - -jasmine.Suite.prototype.results = function() { - return this.queue.results(); -}; - -jasmine.Suite.prototype.add = function(suiteOrSpec) { - this.children_.push(suiteOrSpec); - if (suiteOrSpec instanceof jasmine.Suite) { - this.suites_.push(suiteOrSpec); - this.env.currentRunner().addSuite(suiteOrSpec); - } else { - this.specs_.push(suiteOrSpec); - } - this.queue.add(suiteOrSpec); -}; - -jasmine.Suite.prototype.specs = function() { - return this.specs_; -}; - -jasmine.Suite.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Suite.prototype.children = function() { - return this.children_; -}; - -jasmine.Suite.prototype.execute = function(onComplete) { - var self = this; - this.queue.start(function () { - self.finish(onComplete); - }); -}; -jasmine.WaitsBlock = function(env, timeout, spec) { - this.timeout = timeout; - jasmine.Block.call(this, env, null, spec); -}; - -jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block); - -jasmine.WaitsBlock.prototype.execute = function (onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...'); - } - this.env.setTimeout(function () { - onComplete(); - }, this.timeout); -}; -/** - * A block which waits for some condition to become true, with timeout. - * - * @constructor - * @extends jasmine.Block - * @param {jasmine.Env} env The Jasmine environment. - * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true. - * @param {Function} latchFunction A function which returns true when the desired condition has been met. - * @param {String} message The message to display if the desired condition hasn't been met within the given time period. - * @param {jasmine.Spec} spec The Jasmine spec. - */ -jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) { - this.timeout = timeout || env.defaultTimeoutInterval; - this.latchFunction = latchFunction; - this.message = message; - this.totalTimeSpentWaitingForLatch = 0; - jasmine.Block.call(this, env, null, spec); -}; -jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block); - -jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10; - -jasmine.WaitsForBlock.prototype.execute = function(onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')); - } - var latchFunctionResult; - try { - latchFunctionResult = this.latchFunction.apply(this.spec); - } catch (e) { - this.spec.fail(e); - onComplete(); - return; - } - - if (latchFunctionResult) { - onComplete(); - } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) { - var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen'); - this.spec.fail({ - name: 'timeout', - message: message - }); - - this.abort = true; - onComplete(); - } else { - this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT; - var self = this; - this.env.setTimeout(function() { - self.execute(onComplete); - }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT); - } -}; -// Mock setTimeout, clearTimeout -// Contributed by Pivotal Computer Systems, www.pivotalsf.com - -jasmine.FakeTimer = function() { - this.reset(); - - var self = this; - self.setTimeout = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false); - return self.timeoutsMade; - }; - - self.setInterval = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true); - return self.timeoutsMade; - }; - - self.clearTimeout = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - - self.clearInterval = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - -}; - -jasmine.FakeTimer.prototype.reset = function() { - this.timeoutsMade = 0; - this.scheduledFunctions = {}; - this.nowMillis = 0; -}; - -jasmine.FakeTimer.prototype.tick = function(millis) { - var oldMillis = this.nowMillis; - var newMillis = oldMillis + millis; - this.runFunctionsWithinRange(oldMillis, newMillis); - this.nowMillis = newMillis; -}; - -jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) { - var scheduledFunc; - var funcsToRun = []; - for (var timeoutKey in this.scheduledFunctions) { - scheduledFunc = this.scheduledFunctions[timeoutKey]; - if (scheduledFunc != jasmine.undefined && - scheduledFunc.runAtMillis >= oldMillis && - scheduledFunc.runAtMillis <= nowMillis) { - funcsToRun.push(scheduledFunc); - this.scheduledFunctions[timeoutKey] = jasmine.undefined; - } - } - - if (funcsToRun.length > 0) { - funcsToRun.sort(function(a, b) { - return a.runAtMillis - b.runAtMillis; - }); - for (var i = 0; i < funcsToRun.length; ++i) { - try { - var funcToRun = funcsToRun[i]; - this.nowMillis = funcToRun.runAtMillis; - funcToRun.funcToCall(); - if (funcToRun.recurring) { - this.scheduleFunction(funcToRun.timeoutKey, - funcToRun.funcToCall, - funcToRun.millis, - true); - } - } catch(e) { - } - } - this.runFunctionsWithinRange(oldMillis, nowMillis); - } -}; - -jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) { - this.scheduledFunctions[timeoutKey] = { - runAtMillis: this.nowMillis + millis, - funcToCall: funcToCall, - recurring: recurring, - timeoutKey: timeoutKey, - millis: millis - }; -}; - -/** - * @namespace - */ -jasmine.Clock = { - defaultFakeTimer: new jasmine.FakeTimer(), - - reset: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.reset(); - }, - - tick: function(millis) { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.tick(millis); - }, - - runFunctionsWithinRange: function(oldMillis, nowMillis) { - jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis); - }, - - scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) { - jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring); - }, - - useMock: function() { - if (!jasmine.Clock.isInstalled()) { - var spec = jasmine.getEnv().currentSpec; - spec.after(jasmine.Clock.uninstallMock); - - jasmine.Clock.installMock(); - } - }, - - installMock: function() { - jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer; - }, - - uninstallMock: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.installed = jasmine.Clock.real; - }, - - real: { - setTimeout: jasmine.getGlobal().setTimeout, - clearTimeout: jasmine.getGlobal().clearTimeout, - setInterval: jasmine.getGlobal().setInterval, - clearInterval: jasmine.getGlobal().clearInterval - }, - - assertInstalled: function() { - if (!jasmine.Clock.isInstalled()) { - throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()"); - } - }, - - isInstalled: function() { - return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer; - }, - - installed: null -}; -jasmine.Clock.installed = jasmine.Clock.real; - -//else for IE support -jasmine.getGlobal().setTimeout = function(funcToCall, millis) { - if (jasmine.Clock.installed.setTimeout.apply) { - return jasmine.Clock.installed.setTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.setTimeout(funcToCall, millis); - } -}; - -jasmine.getGlobal().setInterval = function(funcToCall, millis) { - if (jasmine.Clock.installed.setInterval.apply) { - return jasmine.Clock.installed.setInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.setInterval(funcToCall, millis); - } -}; - -jasmine.getGlobal().clearTimeout = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearTimeout(timeoutKey); - } -}; - -jasmine.getGlobal().clearInterval = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearInterval(timeoutKey); - } -}; - -jasmine.version_= { - "major": 1, - "minor": 1, - "build": 0, - "revision": 1315677058 -}; diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png b/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png deleted file mode 100755 index 218f3b43..00000000 Binary files a/server/node_modules/monk/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png and /dev/null differ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/LICENSE b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/LICENSE deleted file mode 100755 index 261eeb9e..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/README.md b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/README.md deleted file mode 100755 index 7428b0d0..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/README.md +++ /dev/null @@ -1,4 +0,0 @@ -kerberos -======== - -Kerberos library for node.js \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/binding.gyp b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/binding.gyp deleted file mode 100755 index 37c3a6a6..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/binding.gyp +++ /dev/null @@ -1,45 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'kerberos', - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'include_dirs': [ '> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = AR($(TOOLSET)) $@ -cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) - -quiet_cmd_alink_thin = AR($(TOOLSET)) $@ -cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) - -# Due to circular dependencies between libraries :(, we wrap the -# special "figure out circular dependencies" flags around the entire -# input list during linking. -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) - -# We support two kinds of shared objects (.so): -# 1) shared_library, which is just bundling together many dependent libraries -# into a link line. -# 2) loadable_module, which is generating a module intended for dlopen(). -# -# They differ only slightly: -# In the former case, we want to package all dependent code into the .so. -# In the latter case, we want to package just the API exposed by the -# outermost module. -# This means shared_library uses --whole-archive, while loadable_module doesn't. -# (Note that --whole-archive is incompatible with the --start-group used in -# normal linking.) - -# Other shared-object link notes: -# - Set SONAME to the library filename so our binaries don't reference -# the local, absolute paths used on the link command-line. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) - -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 1,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,kerberos.target.mk)))),) - include kerberos.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /usr/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/var/www/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/build/config.gypi -I/usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/kasperrt/.node-gyp/0.10.33/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/kasperrt/.node-gyp/0.10.33" "-Dmodule_root_dir=/var/www/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos" binding.gyp -Makefile: $(srcdir)/../../../../../../../../../home/kasperrt/.node-gyp/0.10.33/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile deleted file mode 100755 index 69e964f5..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= ./build/. -.PHONY: all -all: - $(MAKE) kerberos diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/build/config.gypi b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/build/config.gypi deleted file mode 100755 index 5a02ae8b..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/build/config.gypi +++ /dev/null @@ -1,122 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "clang": 0, - "gcc_version": 46, - "host_arch": "x64", - "node_install_npm": "true", - "node_prefix": "/usr", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_openssl": "false", - "node_shared_v8": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_unsafe_optimizations": 0, - "node_use_dtrace": "false", - "node_use_etw": "false", - "node_use_openssl": "true", - "node_use_perfctr": "false", - "node_use_systemtap": "false", - "openssl_no_asm": 0, - "python": "/usr/bin/python", - "target_arch": "x64", - "v8_enable_gdbjit": 0, - "v8_no_strict_aliasing": 1, - "v8_use_snapshot": "false", - "want_separate_host_toolset": 0, - "nodedir": "/home/kasperrt/.node-gyp/0.10.33", - "copy_dev_lib": "true", - "standalone_static_library": 1, - "cache_lock_stale": "60000", - "sign_git_tag": "", - "user_agent": "npm/1.4.28 node/v0.10.33 linux x64", - "always_auth": "", - "bin_links": "true", - "key": "", - "description": "true", - "fetch_retries": "2", - "heading": "npm", - "user": "1000", - "force": "", - "cache_min": "10", - "init_license": "ISC", - "editor": "vi", - "rollback": "true", - "cache_max": "Infinity", - "userconfig": "/home/kasperrt/.npmrc", - "engine_strict": "", - "init_author_name": "", - "init_author_url": "", - "tmp": "/tmp", - "depth": "Infinity", - "save_dev": "", - "usage": "", - "cafile": "", - "https_proxy": "", - "onload_script": "", - "rebuild_bundle": "true", - "save_bundle": "", - "shell": "/bin/zsh", - "prefix": "/usr", - "registry": "https://registry.npmjs.org/", - "browser": "", - "cache_lock_wait": "10000", - "save_optional": "", - "searchopts": "", - "versions": "", - "cache": "/home/kasperrt/.npm", - "ignore_scripts": "", - "searchsort": "name", - "version": "", - "local_address": "", - "viewer": "man", - "color": "true", - "fetch_retry_mintimeout": "10000", - "umask": "18", - "fetch_retry_maxtimeout": "60000", - "message": "%s", - "ca": "", - "cert": "", - "global": "", - "link": "", - "save": "", - "unicode": "true", - "long": "", - "production": "", - "unsafe_perm": "", - "node_version": "0.10.33", - "tag": "latest", - "git_tag_version": "true", - "shrinkwrap": "true", - "fetch_retry_factor": "10", - "npat": "", - "proprietary_attribs": "true", - "save_exact": "", - "strict_ssl": "true", - "username": "", - "dev": "", - "globalconfig": "/usr/etc/npmrc", - "init_module": "/home/kasperrt/.npm-init.js", - "parseable": "", - "globalignorefile": "/usr/etc/npmignore", - "cache_lock_retries": "10", - "save_prefix": "^", - "group": "1000", - "init_author_email": "", - "searchexclude": "", - "git": "git", - "optional": "true", - "email": "", - "json": "", - "spin": "true" - } -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk deleted file mode 100755 index 4bb8ce2b..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk +++ /dev/null @@ -1,145 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := kerberos -DEFS_Debug := \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -fPIC \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -pthread \ - -m64 \ - -g \ - -O0 - -# Flags passed to only C files. -CFLAGS_C_Debug := - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti - -INCS_Debug := \ - -I/home/kasperrt/.node-gyp/0.10.33/src \ - -I/home/kasperrt/.node-gyp/0.10.33/deps/uv/include \ - -I/home/kasperrt/.node-gyp/0.10.33/deps/v8/include \ - -I$(srcdir)/node_modules/nan \ - -I/usr/include/mit-krb5 - -DEFS_Release := \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -fPIC \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -pthread \ - -m64 \ - -O2 \ - -fno-strict-aliasing \ - -fno-tree-vrp \ - -fno-omit-frame-pointer - -# Flags passed to only C files. -CFLAGS_C_Release := - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti - -INCS_Release := \ - -I/home/kasperrt/.node-gyp/0.10.33/src \ - -I/home/kasperrt/.node-gyp/0.10.33/deps/uv/include \ - -I/home/kasperrt/.node-gyp/0.10.33/deps/v8/include \ - -I$(srcdir)/node_modules/nan \ - -I/usr/include/mit-krb5 - -OBJS := \ - $(obj).target/$(TARGET)/lib/kerberos.o \ - $(obj).target/$(TARGET)/lib/worker.o \ - $(obj).target/$(TARGET)/lib/kerberosgss.o \ - $(obj).target/$(TARGET)/lib/base64.o \ - $(obj).target/$(TARGET)/lib/kerberos_context.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -pthread \ - -rdynamic \ - -m64 - -LDFLAGS_Release := \ - -pthread \ - -rdynamic \ - -m64 - -LIBS := - -$(obj).target/kerberos.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(obj).target/kerberos.node: LIBS := $(LIBS) -$(obj).target/kerberos.node: TOOLSET := $(TOOLSET) -$(obj).target/kerberos.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(obj).target/kerberos.node -# Add target alias -.PHONY: kerberos -kerberos: $(builddir)/kerberos.node - -# Copy this to the executable output path. -$(builddir)/kerberos.node: TOOLSET := $(TOOLSET) -$(builddir)/kerberos.node: $(obj).target/kerberos.node FORCE_DO_CMD - $(call do_cmd,copy) - -all_deps += $(builddir)/kerberos.node -# Short alias for building this executable. -.PHONY: kerberos.node -kerberos.node: $(obj).target/kerberos.node $(builddir)/kerberos.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/kerberos.node - diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/builderror.log b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/builderror.log deleted file mode 100755 index 3bfa48eb..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/builderror.log +++ /dev/null @@ -1,15 +0,0 @@ -In file included from ../lib/kerberos.cc:1:0: -../lib/kerberos.h:5:27: fatal error: gssapi/gssapi.h: No such file or directory -compilation terminated. -make: *** [Release/obj.target/kerberos/lib/kerberos.o] Error 1 -gyp ERR! build error -gyp ERR! stack Error: `make` failed with exit code: 2 -gyp ERR! stack at ChildProcess.onExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23) -gyp ERR! stack at ChildProcess.emit (events.js:98:17) -gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:810:12) -gyp ERR! System Linux 3.13.11-03131106-generic -gyp ERR! command "node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" -gyp ERR! cwd /var/www/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos -gyp ERR! node -v v0.10.33 -gyp ERR! node-gyp -v v1.0.1 -gyp ERR! not ok diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/index.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/index.js deleted file mode 100755 index b8c85327..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/index.js +++ /dev/null @@ -1,6 +0,0 @@ -// Get the Kerberos library -module.exports = require('./lib/kerberos'); -// Set up the auth processes -module.exports['processes'] = { - MongoAuthProcess: require('./lib/auth_processes/mongodb').MongoAuthProcess -} \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js deleted file mode 100755 index f1e9231a..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js +++ /dev/null @@ -1,281 +0,0 @@ -var format = require('util').format; - -var MongoAuthProcess = function(host, port, service_name) { - // Check what system we are on - if(process.platform == 'win32') { - this._processor = new Win32MongoProcessor(host, port, service_name); - } else { - this._processor = new UnixMongoProcessor(host, port, service_name); - } -} - -MongoAuthProcess.prototype.init = function(username, password, callback) { - this._processor.init(username, password, callback); -} - -MongoAuthProcess.prototype.transition = function(payload, callback) { - this._processor.transition(payload, callback); -} - -/******************************************************************* - * - * Win32 SSIP Processor for MongoDB - * - *******************************************************************/ -var Win32MongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.ssip = require("../kerberos").SSIP; - // Set up first transition - this._transition = Win32MongoProcessor.first_transition(this); - // Set up service name - service_name = service_name || "mongodb"; - // Set up target - this.target = format("%s/%s", service_name, host); - // Number of retries - this.retries = 10; -} - -Win32MongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - // Save the values used later - this.username = username; - this.password = password; - // Aquire credentials - this.ssip.SecurityCredentials.aquire_kerberos(username, password, function(err, security_credentials) { - if(err) return callback(err); - // Save credentials - self.security_credentials = security_credentials; - // Callback with success - callback(null); - }); -} - -Win32MongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -Win32MongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.ssip.SecurityContext.initialize( - self.security_credentials, - self.target, - payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.second_transition(self); - self.security_context = security_context; - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.second_transition = function(self) { - return function(payload, callback) { - // Perform a step - self.security_context.initialize(self.target, payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - self._transition = Win32MongoProcessor.first_transition(self); - // Retry - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.third_transition(self); - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.third_transition = function(self) { - return function(payload, callback) { - var messageLength = 0; - // Get the raw bytes - var encryptedBytes = new Buffer(payload, 'base64'); - var encryptedMessage = new Buffer(messageLength); - // Copy first byte - encryptedBytes.copy(encryptedMessage, 0, 0, messageLength); - // Set up trailer - var securityTrailerLength = encryptedBytes.length - messageLength; - var securityTrailer = new Buffer(securityTrailerLength); - // Copy the bytes - encryptedBytes.copy(securityTrailer, 0, messageLength, securityTrailerLength); - - // Types used - var SecurityBuffer = self.ssip.SecurityBuffer; - var SecurityBufferDescriptor = self.ssip.SecurityBufferDescriptor; - - // Set up security buffers - var buffers = [ - new SecurityBuffer(SecurityBuffer.DATA, encryptedBytes) - , new SecurityBuffer(SecurityBuffer.STREAM, securityTrailer) - ]; - - // Set up the descriptor - var descriptor = new SecurityBufferDescriptor(buffers); - - // Decrypt the data - self.security_context.decryptMessage(descriptor, function(err, security_context) { - if(err) return callback(err); - - var length = 4; - if(self.username != null) { - length += self.username.length; - } - - var bytesReceivedFromServer = new Buffer(length); - bytesReceivedFromServer[0] = 0x01; // NO_PROTECTION - bytesReceivedFromServer[1] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[2] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[3] = 0x00; // NO_PROTECTION - - if(self.username != null) { - var authorization_id_bytes = new Buffer(self.username, 'utf8'); - authorization_id_bytes.copy(bytesReceivedFromServer, 4, 0); - } - - self.security_context.queryContextAttributes(0x00, function(err, sizes) { - if(err) return callback(err); - - var buffers = [ - new SecurityBuffer(SecurityBuffer.TOKEN, new Buffer(sizes.securityTrailer)) - , new SecurityBuffer(SecurityBuffer.DATA, bytesReceivedFromServer) - , new SecurityBuffer(SecurityBuffer.PADDING, new Buffer(sizes.blockSize)) - ] - - var descriptor = new SecurityBufferDescriptor(buffers); - - self.security_context.encryptMessage(descriptor, 0x80000001, function(err, security_context) { - if(err) return callback(err); - callback(null, security_context.payload); - }); - }); - }); - } -} - -/******************************************************************* - * - * UNIX MIT Kerberos processor - * - *******************************************************************/ -var UnixMongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.Kerberos = require("../kerberos").Kerberos; - this.kerberos = new this.Kerberos(); - service_name = service_name || "mongodb"; - // Set up first transition - this._transition = UnixMongoProcessor.first_transition(this); - // Set up target - this.target = format("%s@%s", service_name, host); - // Number of retries - this.retries = 10; -} - -UnixMongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - this.username = username; - this.password = password; - // Call client initiate - this.kerberos.authGSSClientInit( - self.target - , this.Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - self.context = context; - // Return the context - callback(null, context); - }); -} - -UnixMongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -UnixMongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, '', function(err, result) { - if(err) return callback(err); - // Set up the next step - self._transition = UnixMongoProcessor.second_transition(self); - // Return the payload - callback(null, self.context.response); - }) - } -} - -UnixMongoProcessor.second_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, payload, function(err, result) { - if(err && self.retries == 0) return callback(err); - // Attempt to re-establish a context - if(err) { - // Adjust the number of retries - self.retries = self.retries - 1; - // Call same step again - return self.transition(payload, callback); - } - - // Set up the next step - self._transition = UnixMongoProcessor.third_transition(self); - // Return the payload - callback(null, self.context.response || ''); - }); - } -} - -UnixMongoProcessor.third_transition = function(self) { - return function(payload, callback) { - // GSS Client Unwrap - self.kerberos.authGSSClientUnwrap(self.context, payload, function(err, result) { - if(err) return callback(err, false); - - // Wrap the response - self.kerberos.authGSSClientWrap(self.context, self.context.response, self.username, function(err, result) { - if(err) return callback(err, false); - // Set up the next step - self._transition = UnixMongoProcessor.fourth_transition(self); - // Return the payload - callback(null, self.context.response); - }); - }); - } -} - -UnixMongoProcessor.fourth_transition = function(self) { - return function(payload, callback) { - // Clean up context - self.kerberos.authGSSClientClean(self.context, function(err, result) { - if(err) return callback(err, false); - // Set the transition to null - self._transition = null; - // Callback with valid authentication - callback(null, true); - }); - } -} - -// Set the process -exports.MongoAuthProcess = MongoAuthProcess; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/base64.c b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/base64.c deleted file mode 100755 index aca0a61c..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/base64.c +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -#include "base64.h" - -#include -#include -#include -#include - -void die2(const char *message) { - if(errno) { - perror(message); - } else { - printf("ERROR: %s\n", message); - } - - exit(1); -} - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - if(result == NULL) die2("Memory allocation failed"); - char *out = result; - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - unsigned char oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - *rlen = 0; - int c1, c2, c3, c4; - - int vlen = strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - if(result == NULL) die2("Memory allocation failed"); - unsigned char *out = result; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/base64.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/base64.h deleted file mode 100755 index 9152e6a3..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/base64.h +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ -#ifndef BASE64_H -#define BASE64_H - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); - -#endif \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc deleted file mode 100755 index 7744a9de..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc +++ /dev/null @@ -1,592 +0,0 @@ -#include "kerberos.h" -#include -#include -#include "worker.h" -#include "kerberos_context.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -void die(const char *message) { - if(errno) { - perror(message); - } else { - printf("ERROR: %s\n", message); - } - - exit(1); -} - -// Call structs -typedef struct AuthGSSClientCall { - uint32_t flags; - char *uri; -} AuthGSSClientCall; - -typedef struct AuthGSSClientStepCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientStepCall; - -typedef struct AuthGSSClientUnwrapCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientUnwrapCall; - -typedef struct AuthGSSClientWrapCall { - KerberosContext *context; - char *challenge; - char *user_name; -} AuthGSSClientWrapCall; - -typedef struct AuthGSSClientCleanCall { - KerberosContext *context; -} AuthGSSClientCleanCall; - -Kerberos::Kerberos() : ObjectWrap() { -} - -Persistent Kerberos::constructor_template; - -void Kerberos::Initialize(v8::Handle target) { - // Grab the scope of the call from Node - NanScope(); - - // Define a new function template - Local t = NanNew(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(NanNew("Kerberos")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(t, "authGSSClientInit", AuthGSSClientInit); - NODE_SET_PROTOTYPE_METHOD(t, "authGSSClientStep", AuthGSSClientStep); - NODE_SET_PROTOTYPE_METHOD(t, "authGSSClientUnwrap", AuthGSSClientUnwrap); - NODE_SET_PROTOTYPE_METHOD(t, "authGSSClientWrap", AuthGSSClientWrap); - NODE_SET_PROTOTYPE_METHOD(t, "authGSSClientClean", AuthGSSClientClean); - - NanAssignPersistent(constructor_template, t); - - // Set the symbol - target->ForceSet(NanNew("Kerberos"), t->GetFunction()); -} - -NAN_METHOD(Kerberos::New) { - NanScope(); - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(args.This()); - NanReturnValue(args.This()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientInit(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - - // Allocate state - state = (gss_client_state *)malloc(sizeof(gss_client_state)); - if(state == NULL) die("Memory allocation failed"); - - // Unpack the parameter data struct - AuthGSSClientCall *call = (AuthGSSClientCall *)worker->parameters; - // Start the kerberos client - response = authenticate_gss_client_init(call->uri, call->flags, state); - - // Release the parameter struct memory - free(call->uri); - free(call); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - free(state); - } else { - worker->return_value = state; - } - - // Free structure - free(response); -} - -static Handle _map_authGSSClientInit(Worker *worker) { - KerberosContext *context = KerberosContext::New(); - context->state = (gss_client_state *)worker->return_value; - return NanObjectWrapHandle(context); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientInit) { - NanScope(); - - // Ensure valid call - if(args.Length() != 3) return NanThrowError("Requires a service string uri, integer flags and a callback function"); - if(args.Length() == 3 && !args[0]->IsString() && !args[1]->IsInt32() && !args[2]->IsFunction()) - return NanThrowError("Requires a service string uri, integer flags and a callback function"); - - Local service = args[0]->ToString(); - // Convert uri string to c-string - char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); - if(service_str == NULL) die("Memory allocation failed"); - - // Write v8 string to c-string - service->WriteUtf8(service_str); - - // Allocate a structure - AuthGSSClientCall *call = (AuthGSSClientCall *)calloc(1, sizeof(AuthGSSClientCall)); - if(call == NULL) die("Memory allocation failed"); - call->flags =args[1]->ToInt32()->Uint32Value(); - call->uri = service_str; - - // Unpack the callback - Local callbackHandle = Local::Cast(args[2]); - NanCallback *callback = new NanCallback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientInit; - worker->mapper = _map_authGSSClientInit; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - // Return no value as it's callback based - NanReturnValue(NanUndefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientStep -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientStep(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)worker->parameters; - // Get the state - state = call->context->state; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_step(state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Handle _map_authGSSClientStep(Worker *worker) { - NanScope(); - // Return the return code - return NanNew(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientStep) { - NanScope(); - - // Ensure valid call - if(args.Length() != 2 && args.Length() != 3) return NanThrowError("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 2 && !KerberosContext::HasInstance(args[0])) return NanThrowError("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString()) return NanThrowError("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // If we have a challenge string - if(args.Length() == 3) { - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - if(challenge_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - } - - // Allocate a structure - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)calloc(1, sizeof(AuthGSSClientCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callbackHandle = Local::Cast(args[2]); - NanCallback *callback = new NanCallback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientStep; - worker->mapper = _map_authGSSClientStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - NanReturnValue(NanUndefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientUnwrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientUnwrap(Worker *worker) { - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)worker->parameters; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_unwrap(call->context->state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Handle _map_authGSSClientUnwrap(Worker *worker) { - NanScope(); - // Return the return code - return NanNew(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientUnwrap) { - NanScope(); - - // Ensure valid call - if(args.Length() != 2 && args.Length() != 3) return NanThrowError("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 2 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsFunction()) return NanThrowError("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsFunction()) return NanThrowError("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // If we have a challenge string - if(args.Length() == 3) { - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - if(challenge_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - } - - // Allocate a structure - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)calloc(1, sizeof(AuthGSSClientUnwrapCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callbackHandle = args.Length() == 3 ? Local::Cast(args[2]) : Local::Cast(args[1]); - NanCallback *callback = new NanCallback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientUnwrap; - worker->mapper = _map_authGSSClientUnwrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - // return scope.Close(NanUndefined()); - NanReturnValue(NanUndefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientWrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientWrap(Worker *worker) { - gss_client_response *response; - char *user_name = NULL; - - // Unpack the parameter data struct - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)worker->parameters; - user_name = call->user_name; - - // Check what kind of challenge we have - if(call->user_name == NULL) { - user_name = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_wrap(call->context->state, call->challenge, user_name); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - if(call->user_name != NULL) free(call->user_name); - free(call); - free(response); -} - -static Handle _map_authGSSClientWrap(Worker *worker) { - NanScope(); - // Return the return code - return NanNew(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientWrap) { - NanScope(); - - // Ensure valid call - if(args.Length() != 3 && args.Length() != 4) return NanThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsFunction()) return NanThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(args.Length() == 4 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsString() && !args[2]->IsFunction()) return NanThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - - // Challenge string - char *challenge_str = NULL; - char *user_name_str = NULL; - - // Let's unpack the kerberos context - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - if(challenge_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - - // If we have a user string - if(args.Length() == 4) { - // Unpack user name - Local user_name = args[2]->ToString(); - // Convert uri string to c-string - user_name_str = (char *)calloc(user_name->Utf8Length() + 1, sizeof(char)); - if(user_name_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - user_name->WriteUtf8(user_name_str); - } - - // Allocate a structure - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)calloc(1, sizeof(AuthGSSClientWrapCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - call->challenge = challenge_str; - call->user_name = user_name_str; - - // Unpack the callback - Local callbackHandle = args.Length() == 4 ? Local::Cast(args[3]) : Local::Cast(args[2]); - NanCallback *callback = new NanCallback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientWrap; - worker->mapper = _map_authGSSClientWrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - NanReturnValue(NanUndefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientWrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientClean(Worker *worker) { - gss_client_response *response; - - // Unpack the parameter data struct - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)worker->parameters; - - // Perform authentication step - response = authenticate_gss_client_clean(call->context->state); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - free(call); - free(response); -} - -static Handle _map_authGSSClientClean(Worker *worker) { - NanScope(); - // Return the return code - return NanNew(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientClean) { - NanScope(); - - // // Ensure valid call - if(args.Length() != 2) return NanThrowError("Requires a GSS context and callback function"); - if(!KerberosContext::HasInstance(args[0]) && !args[1]->IsFunction()) return NanThrowError("Requires a GSS context and callback function"); - - // Let's unpack the kerberos context - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // Allocate a structure - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)calloc(1, sizeof(AuthGSSClientCleanCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - - // Unpack the callback - Local callbackHandle = Local::Cast(args[1]); - NanCallback *callback = new NanCallback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientClean; - worker->mapper = _map_authGSSClientClean; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - NanReturnValue(NanUndefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Kerberos::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void Kerberos::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - NanScope(); - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - Local err = v8::Exception::Error(NanNew(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NanNew("code"), NanNew(worker->error_code)); - Local args[2] = { err, NanNull() }; - // Execute the error - v8::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(args), args); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - Handle result = worker->mapper(worker); - // Set up the callback with a null first - Handle args[2] = { NanNull(), result}; - - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(args), args); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - delete worker->callback; - delete worker; -} - -// Exporting function -extern "C" void init(Handle target) { - NanScope(); - Kerberos::Initialize(target); - KerberosContext::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h deleted file mode 100755 index b037d4eb..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include -#include - -#include "nan.h" -#include -#include - -#include "util.h" - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Method available - static NAN_METHOD(AuthGSSClientInit); - static NAN_METHOD(AuthGSSClientStep); - static NAN_METHOD(AuthGSSClientUnwrap); - static NAN_METHOD(AuthGSSClientWrap); - static NAN_METHOD(AuthGSSClientClean); - -private: - static NAN_METHOD(New); - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js deleted file mode 100755 index b1a701ba..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js +++ /dev/null @@ -1,91 +0,0 @@ -var kerberos = require('../build/Release/kerberos') - , KerberosNative = kerberos.Kerberos; - -var Kerberos = function() { - this._native_kerberos = new KerberosNative(); -} - -Kerberos.prototype.authGSSClientInit = function(uri, flags, callback) { - return this._native_kerberos.authGSSClientInit(uri, flags, callback); -} - -Kerberos.prototype.authGSSClientStep = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientStep(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientUnwrap = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientUnwrap(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientWrap = function(context, challenge, user_name, callback) { - if(typeof user_name == 'function') { - callback = user_name; - user_name = ''; - } - - return this._native_kerberos.authGSSClientWrap(context, challenge, user_name, callback); -} - -Kerberos.prototype.authGSSClientClean = function(context, callback) { - return this._native_kerberos.authGSSClientClean(context, callback); -} - -Kerberos.prototype.acquireAlternateCredentials = function(user_name, password, domain) { - return this._native_kerberos.acquireAlternateCredentials(user_name, password, domain); -} - -Kerberos.prototype.prepareOutboundPackage = function(principal, inputdata) { - return this._native_kerberos.prepareOutboundPackage(principal, inputdata); -} - -Kerberos.prototype.decryptMessage = function(challenge) { - return this._native_kerberos.decryptMessage(challenge); -} - -Kerberos.prototype.encryptMessage = function(challenge) { - return this._native_kerberos.encryptMessage(challenge); -} - -Kerberos.prototype.queryContextAttribute = function(attribute) { - if(typeof attribute != 'number' && attribute != 0x00) throw new Error("Attribute not supported"); - return this._native_kerberos.queryContextAttribute(attribute); -} - -// Some useful result codes -Kerberos.AUTH_GSS_CONTINUE = 0; -Kerberos.AUTH_GSS_COMPLETE = 1; - -// Some useful gss flags -Kerberos.GSS_C_DELEG_FLAG = 1; -Kerberos.GSS_C_MUTUAL_FLAG = 2; -Kerberos.GSS_C_REPLAY_FLAG = 4; -Kerberos.GSS_C_SEQUENCE_FLAG = 8; -Kerberos.GSS_C_CONF_FLAG = 16; -Kerberos.GSS_C_INTEG_FLAG = 32; -Kerberos.GSS_C_ANON_FLAG = 64; -Kerberos.GSS_C_PROT_READY_FLAG = 128; -Kerberos.GSS_C_TRANS_FLAG = 256; - -// Export Kerberos class -exports.Kerberos = Kerberos; - -// If we have SSPI (windows) -if(kerberos.SecurityCredentials) { - // Put all SSPI classes in it's own namespace - exports.SSIP = { - SecurityCredentials: require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext: require('./win32/wrappers/security_context').SecurityContext - , SecurityBuffer: require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor: require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - } -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc deleted file mode 100755 index cc38e0d3..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc +++ /dev/null @@ -1,77 +0,0 @@ -#include "kerberos_context.h" - -Persistent KerberosContext::constructor_template; - -KerberosContext::KerberosContext() : ObjectWrap() { -} - -KerberosContext::~KerberosContext() { -} - -KerberosContext* KerberosContext::New() { - NanScope(); - Local obj = NanNew(constructor_template)->GetFunction()->NewInstance(); - KerberosContext *kerberos_context = ObjectWrap::Unwrap(obj); - return kerberos_context; -} - -NAN_METHOD(KerberosContext::New) { - NanScope(); - // Create code object - KerberosContext *kerberos_context = new KerberosContext(); - // Wrap it - kerberos_context->Wrap(args.This()); - // Return the object - NanReturnValue(args.This()); -} - -void KerberosContext::Initialize(v8::Handle target) { - // Grab the scope of the call from Node - NanScope(); - - // Define a new function template - // Local t = NanNew(New); - Local t = NanNew(static_cast(New)); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(NanNew("KerberosContext")); - - // Get prototype - Local proto = t->PrototypeTemplate(); - - // Getter for the response - proto->SetAccessor(NanNew("response"), KerberosContext::ResponseGetter); - - // Set persistent - NanAssignPersistent(constructor_template, t); - - // Set the symbol - target->ForceSet(NanNew("KerberosContext"), t->GetFunction()); -} - -// -// Response Setter / Getter -NAN_GETTER(KerberosContext::ResponseGetter) { - NanScope(); - gss_client_state *state; - - // Unpack the object - KerberosContext *context = ObjectWrap::Unwrap(args.This()); - // Let's grab the response - state = context->state; - // No state no response - if(state == NULL || state->response == NULL) { - NanReturnValue(NanNull()); - } else { - // Return the response - NanReturnValue(NanNew(state->response)); - } -} - - - - - - - - - diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h deleted file mode 100755 index dd00f1d4..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef KERBEROS_CONTEXT_H -#define KERBEROS_CONTEXT_H - -#include -#include -#include -#include - -#include "nan.h" -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class KerberosContext : public ObjectWrap { - -public: - KerberosContext(); - ~KerberosContext(); - - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return NanNew(constructor_template)->HasInstance(obj); - }; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Public constructor - static KerberosContext* New(); - - // Handle to the kerberos context - gss_client_state *state; - -private: - static NAN_METHOD(New); - static NAN_GETTER(ResponseGetter); -}; -#endif \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c deleted file mode 100755 index 8e55b62c..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c +++ /dev/null @@ -1,693 +0,0 @@ -/** - * Copyright (c) 2006-2010 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -#include "kerberosgss.h" - -#include "base64.h" - -#include -#include -#include -#include -#include - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - -void die1(const char *message) { - if(errno) { - perror(message); - } else { - printf("ERROR: %s\n", message); - } - - exit(1); -} - -static void set_gss_error(OM_uint32 err_maj, OM_uint32 err_min); - -/*extern PyObject *GssException_class; -extern PyObject *KrbException_class; - -char* server_principal_details(const char* service, const char* hostname) -{ - char match[1024]; - int match_len = 0; - char* result = NULL; - - int code; - krb5_context kcontext; - krb5_keytab kt = NULL; - krb5_kt_cursor cursor = NULL; - krb5_keytab_entry entry; - char* pname = NULL; - - // Generate the principal prefix we want to match - snprintf(match, 1024, "%s/%s@", service, hostname); - match_len = strlen(match); - - code = krb5_init_context(&kcontext); - if (code) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot initialize Kerberos5 context", code)); - return NULL; - } - - if ((code = krb5_kt_default(kcontext, &kt))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get default keytab", code)); - goto end; - } - - if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get sequence cursor from keytab", code)); - goto end; - } - - while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0) - { - if ((code = krb5_unparse_name(kcontext, entry.principal, &pname))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot parse principal name from keytab", code)); - goto end; - } - - if (strncmp(pname, match, match_len) == 0) - { - result = malloc(strlen(pname) + 1); - strcpy(result, pname); - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - break; - } - - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - } - - if (result == NULL) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Principal not found in keytab", -1)); - } - -end: - if (cursor) - krb5_kt_end_seq_get(kcontext, kt, &cursor); - if (kt) - krb5_kt_close(kcontext, kt); - krb5_free_context(kcontext); - - return result; -} -*/ -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_COMPLETE; - - state->server_name = GSS_C_NO_NAME; - state->context = GSS_C_NO_CONTEXT; - state->gss_flags = gss_flags; - state->username = NULL; - state->response = NULL; - - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, gss_krb5_nt_service_name, &state->server_name); - - if (GSS_ERROR(maj_stat)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - -end: - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_clean(gss_client_state *state) { - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - gss_client_response *response = NULL; - - if(state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - - if(state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - - if(state->username != NULL) { - free(state->username); - state->username = NULL; - } - - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_step(gss_client_state* state, const char* challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - - // Always clear out the old response - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_init_sec_context(&min_stat, - GSS_C_NO_CREDENTIAL, - &state->context, - state->server_name, - GSS_C_NO_OID, - (OM_uint32)state->gss_flags, - 0, - GSS_C_NO_CHANNEL_BINDINGS, - &input_token, - NULL, - &output_token, - NULL, - NULL); - - if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE; - // Grab the client response to send back to the server - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Try to get the user name if we have completed all GSS operations - if (ret == AUTH_GSS_COMPLETE) { - gss_name_t gssuser = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL); - - if(GSS_ERROR(maj_stat)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - gss_buffer_desc name_token; - name_token.length = 0; - maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL); - - if(GSS_ERROR(maj_stat)) { - if(name_token.value) - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - state->username = (char *)malloc(name_token.length + 1); - if(state->username == NULL) die1("Memory allocation failed"); - strncpy(state->username, (char*) name_token.value, name_token.length); - state->username[name_token.length] = 0; - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - } - } - -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_unwrap(gss_client_state *state, const char *challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_unwrap(&min_stat, - state->context, - &input_token, - &output_token, - NULL, - NULL); - - if(maj_stat != GSS_S_COMPLETE) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - ret = AUTH_GSS_COMPLETE; - } - - // Grab the client response - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - gss_release_buffer(&min_stat, &output_token); - } -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - char buf[4096], server_conf_flags; - unsigned long buf_size; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - if(user) { - // get bufsize - server_conf_flags = ((char*) input_token.value)[0]; - ((char*) input_token.value)[0] = 0; - buf_size = ntohl(*((long *) input_token.value)); - free(input_token.value); -#ifdef PRINTFS - printf("User: %s, %c%c%c\n", user, - server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-', - server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-', - server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-'); - printf("Maximum GSS token size is %ld\n", buf_size); -#endif - - // agree to terms (hack!) - buf_size = htonl(buf_size); // not relevant without integrity/privacy - memcpy(buf, &buf_size, 4); - buf[0] = GSS_AUTH_P_NONE; - // server decides if principal can log in as user - strncpy(buf + 4, user, sizeof(buf) - 4); - input_token.value = buf; - input_token.length = 4 + strlen(user); - } - - // Do GSSAPI wrap - maj_stat = gss_wrap(&min_stat, - state->context, - 0, - GSS_C_QOP_DEFAULT, - &input_token, - NULL, - &output_token); - - if (maj_stat != GSS_S_COMPLETE) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else - ret = AUTH_GSS_COMPLETE; - // Grab the client response to send back to the server - if (output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; - gss_release_buffer(&min_stat, &output_token); - } -end: - if (output_token.value) - gss_release_buffer(&min_stat, &output_token); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -int authenticate_gss_server_init(const char *service, gss_server_state *state) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_COMPLETE; - - state->context = GSS_C_NO_CONTEXT; - state->server_name = GSS_C_NO_NAME; - state->client_name = GSS_C_NO_NAME; - state->server_creds = GSS_C_NO_CREDENTIAL; - state->client_creds = GSS_C_NO_CREDENTIAL; - state->username = NULL; - state->targetname = NULL; - state->response = NULL; - - // Server name may be empty which means we aren't going to create our own creds - size_t service_len = strlen(service); - if (service_len != 0) - { - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_HOSTBASED_SERVICE, &state->server_name); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - - // Get credentials - maj_stat = gss_acquire_cred(&min_stat, state->server_name, GSS_C_INDEFINITE, - GSS_C_NO_OID_SET, GSS_C_ACCEPT, &state->server_creds, NULL, NULL); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - } - -end: - return ret; -} - -int authenticate_gss_server_clean(gss_server_state *state) -{ - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - - if (state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - if (state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - if (state->client_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->client_name); - if (state->server_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->server_creds); - if (state->client_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->client_creds); - if (state->username != NULL) - { - free(state->username); - state->username = NULL; - } - if (state->targetname != NULL) - { - free(state->targetname); - state->targetname = NULL; - } - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - - return ret; -} - -/*int authenticate_gss_server_step(gss_server_state *state, const char *challenge) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) - { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - else - { - PyErr_SetString(KrbException_class, "No challenge parameter in request from client"); - ret = AUTH_GSS_ERROR; - goto end; - } - - maj_stat = gss_accept_sec_context(&min_stat, - &state->context, - state->server_creds, - &input_token, - GSS_C_NO_CHANNEL_BINDINGS, - &state->client_name, - NULL, - &output_token, - NULL, - NULL, - &state->client_creds); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - - // Grab the server response to send back to the client - if (output_token.length) - { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Get the user name - maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - state->username = (char *)malloc(output_token.length + 1); - strncpy(state->username, (char*) output_token.value, output_token.length); - state->username[output_token.length] = 0; - - // Get the target name if no server creds were supplied - if (state->server_creds == GSS_C_NO_CREDENTIAL) - { - gss_name_t target_name = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - state->targetname = (char *)malloc(output_token.length + 1); - strncpy(state->targetname, (char*) output_token.value, output_token.length); - state->targetname[output_token.length] = 0; - } - - ret = AUTH_GSS_COMPLETE; - -end: - if (output_token.length) - gss_release_buffer(&min_stat, &output_token); - if (input_token.value) - free(input_token.value); - return ret; -} -*/ - -static void set_gss_error(OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char buf_maj[512]; - char buf_min[512]; - - do { - maj_stat = gss_display_status (&min_stat, - err_maj, - GSS_C_GSS_CODE, - GSS_C_NO_OID, - &msg_ctx, - &status_string); - if(GSS_ERROR(maj_stat)) - break; - - strncpy(buf_maj, (char*) status_string.value, sizeof(buf_maj)); - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status (&min_stat, - err_min, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, - &status_string); - if (!GSS_ERROR(maj_stat)) { - - strncpy(buf_min, (char*) status_string.value , sizeof(buf_min)); - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); -} - -gss_client_response *gss_error(OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char *buf_maj = calloc(512, sizeof(char)); - if(buf_maj == NULL) die1("Memory allocation failed"); - char *buf_min = calloc(512, sizeof(char)); - if(buf_min == NULL) die1("Memory allocation failed"); - char *message = NULL; - gss_client_response *response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - - do { - maj_stat = gss_display_status (&min_stat, - err_maj, - GSS_C_GSS_CODE, - GSS_C_NO_OID, - &msg_ctx, - &status_string); - if(GSS_ERROR(maj_stat)) - break; - - strncpy(buf_maj, (char*) status_string.value, 512); - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status (&min_stat, - err_min, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, - &status_string); - if(!GSS_ERROR(maj_stat)) { - strncpy(buf_min, (char*) status_string.value , 512); - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); - - // Join the strings - message = calloc(1026, 1); - if(message == NULL) die1("Memory allocation failed"); - // Join the two messages - sprintf(message, "%s, %s", buf_maj, buf_min); - // Free data - free(buf_min); - free(buf_maj); - // Set the message - response->message = message; - // Return the message - return response; -} - -#pragma clang diagnostic pop - diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h deleted file mode 100755 index 58ac0b71..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2006-2009 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ -#ifndef KERBEROS_GSS_H -#define KERBEROS_GSS_H - -#include -#include -#include - -#define krb5_get_err_text(context,code) error_message(code) - -#define AUTH_GSS_ERROR -1 -#define AUTH_GSS_COMPLETE 1 -#define AUTH_GSS_CONTINUE 0 - -#define GSS_AUTH_P_NONE 1 -#define GSS_AUTH_P_INTEGRITY 2 -#define GSS_AUTH_P_PRIVACY 4 - -typedef struct { - int return_code; - char *message; -} gss_client_response; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - long int gss_flags; - char* username; - char* response; -} gss_client_state; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - gss_name_t client_name; - gss_cred_id_t server_creds; - gss_cred_id_t client_creds; - char* username; - char* targetname; - char* response; -} gss_server_state; - -// char* server_principal_details(const char* service, const char* hostname); - -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state); -gss_client_response *authenticate_gss_client_clean(gss_client_state *state); -gss_client_response *authenticate_gss_client_step(gss_client_state *state, const char *challenge); -gss_client_response *authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge); -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user); - -int authenticate_gss_server_init(const char* service, gss_server_state* state); -int authenticate_gss_server_clean(gss_server_state *state); -// int authenticate_gss_server_step(gss_server_state *state, const char *challenge); - -gss_client_response *gss_error(OM_uint32 err_maj, OM_uint32 err_min); -#endif diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/sspi.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/sspi.js deleted file mode 100755 index d9120fba..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/sspi.js +++ /dev/null @@ -1,15 +0,0 @@ -// Load the native SSPI classes -var kerberos = require('../build/Release/kerberos') - , Kerberos = kerberos.Kerberos - , SecurityBuffer = require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor = require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - , SecurityCredentials = require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext = require('./win32/wrappers/security_context').SecurityContext; -var SSPI = function() { -} - -exports.SSPI = SSPI; -exports.SecurityBuffer = SecurityBuffer; -exports.SecurityBufferDescriptor = SecurityBufferDescriptor; -exports.SecurityCredentials = SecurityCredentials; -exports.SecurityContext = SecurityContext; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c deleted file mode 100755 index 502a021c..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -#include "base64.h" - -#include -#include - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - char *out = result; - unsigned char oval; - - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - int c1, c2, c3, c4; - int vlen = (int)strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - unsigned char *out = result; - *rlen = 0; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h deleted file mode 100755 index f0e1f061..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc deleted file mode 100755 index c40be182..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc +++ /dev/null @@ -1,53 +0,0 @@ -#include "kerberos.h" -#include -#include -#include "base64.h" -#include "wrappers/security_buffer.h" -#include "wrappers/security_buffer_descriptor.h" -#include "wrappers/security_context.h" -#include "wrappers/security_credentials.h" - -Persistent Kerberos::constructor_template; - -Kerberos::Kerberos() : ObjectWrap() { -} - -void Kerberos::Initialize(v8::Handle target) { - // Grab the scope of the call from Node - NanScope(); - - // Define a new function template - Local t = NanNew(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(NanNew("Kerberos")); - - // Set persistent - NanAssignPersistent(constructor_template, t); - - // Set the symbol - target->ForceSet(NanNew("Kerberos"), t->GetFunction()); -} - -NAN_METHOD(Kerberos::New) { - NanScope(); - // Load the security.dll library - load_library(); - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(args.This()); - // Return the object - NanReturnValue(args.This()); -} - -// Exporting function -extern "C" void init(Handle target) { - NanScope(); - Kerberos::Initialize(target); - SecurityContext::Initialize(target); - SecurityBuffer::Initialize(target); - SecurityBufferDescriptor::Initialize(target); - SecurityCredentials::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h deleted file mode 100755 index 579d04e1..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include -#include "nan.h" - -extern "C" { - #include "kerberos_sspi.h" - #include "base64.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Method available - static NAN_METHOD(AcquireAlternateCredentials); - static NAN_METHOD(PrepareOutboundPackage); - static NAN_METHOD(DecryptMessage); - static NAN_METHOD(EncryptMessage); - static NAN_METHOD(QueryContextAttributes); - -private: - static NAN_METHOD(New); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - // package info - SecPkgInfo m_PkgInfo; - // context - CtxtHandle m_Context; - // Do we have a context - bool m_HaveContext; - // Attributes - DWORD CtxtAttr; - - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c deleted file mode 100755 index d75c9ab0..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c +++ /dev/null @@ -1,244 +0,0 @@ -#include "kerberos_sspi.h" -#include -#include - -static HINSTANCE _sspi_security_dll = NULL; -static HINSTANCE _sspi_secur32_dll = NULL; - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) { - // Create function pointer instance - encryptMessage_fn pfn_encryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function to library method - pfn_encryptMessage = (encryptMessage_fn)GetProcAddress(_sspi_security_dll, "EncryptMessage"); - // Check if the we managed to map function pointer - if(!pfn_encryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo); -} - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - acquireCredentialsHandle_fn pfn_acquireCredentialsHandle = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleW"); - #else - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_acquireCredentialsHandle) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Status - status = (*pfn_acquireCredentialsHandle)(pszPrincipal, pszPackage, fCredentialUse, - pvLogonId, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry - ); - - // Call the function - return status; -} - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(PCtxtHandle phContext) { - // Create function pointer instance - deleteSecurityContext_fn pfn_deleteSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_deleteSecurityContext = (deleteSecurityContext_fn)GetProcAddress(_sspi_security_dll, "DeleteSecurityContext"); - - // Check if the we managed to map function pointer - if(!pfn_deleteSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_deleteSecurityContext)(phContext); -} - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP) { - // Create function pointer instance - decryptMessage_fn pfn_decryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_decryptMessage = (decryptMessage_fn)GetProcAddress(_sspi_security_dll, "DecryptMessage"); - - // Check if the we managed to map function pointer - if(!pfn_decryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_decryptMessage)(phContext, pMessage, MessageSeqNo, pfQOP); -} - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, PCtxtHandle phContext, - LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, - PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, - unsigned long * pfContextAttr, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - initializeSecurityContext_fn pfn_initializeSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextW"); - #else - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_initializeSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Execute intialize context - status = (*pfn_initializeSecurityContext)( - phCredential, phContext, pszTargetName, fContextReq, - Reserved1, TargetDataRep, pInput, Reserved2, - phNewContext, pOutput, pfContextAttr, ptsExpiry - ); - - // Call the function - return status; -} -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer -) { - // Create function pointer instance - queryContextAttributes_fn pfn_queryContextAttributes = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - #ifdef _UNICODE - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesW"); - #else - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_queryContextAttributes) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_queryContextAttributes)( - phContext, ulAttribute, pBuffer - ); -} - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface() { - INIT_SECURITY_INTERFACE InitSecurityInterface; - PSecurityFunctionTable pSecurityInterface = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return NULL; - - #ifdef _UNICODE - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceW")); - #else - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceA")); - #endif - - if(!InitSecurityInterface) { - printf (TEXT("Failed in getting the function address, Error: %x"), GetLastError ()); - return NULL; - } - - // Use InitSecurityInterface to get the function table. - pSecurityInterface = (*InitSecurityInterface)(); - - if(!pSecurityInterface) { - printf (TEXT("Failed in getting the function table, Error: %x"), GetLastError ()); - return NULL; - } - - return pSecurityInterface; -} - -/** - * Load security.dll dynamically - */ -int load_library() { - DWORD err; - // Load the library - _sspi_security_dll = LoadLibrary("security.dll"); - - // Check if the library loaded - if(_sspi_security_dll == NULL) { - err = GetLastError(); - return err; - } - - // Load the library - _sspi_secur32_dll = LoadLibrary("secur32.dll"); - - // Check if the library loaded - if(_sspi_secur32_dll == NULL) { - err = GetLastError(); - return err; - } - - return 0; -} \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h deleted file mode 100755 index a3008dc5..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef SSPI_C_H -#define SSPI_C_H - -#define SECURITY_WIN32 1 - -#include -#include - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo); - -typedef DWORD (WINAPI *encryptMessage_fn)(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo); - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, // Name of principal - LPSTR pszPackage, // Name of package - unsigned long fCredentialUse, // Flags indicating use - void * pvLogonId, // Pointer to logon ID - void * pAuthData, // Package specific data - SEC_GET_KEY_FN pGetKeyFn, // Pointer to GetKey() func - void * pvGetKeyArgument, // Value to pass to GetKey() - PCredHandle phCredential, // (out) Cred Handle - PTimeStamp ptsExpiry // (out) Lifetime (optional) -); - -typedef DWORD (WINAPI *acquireCredentialsHandle_fn)( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry - ); - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext( - PCtxtHandle phContext // Context to delete -); - -typedef DWORD (WINAPI *deleteSecurityContext_fn)(PCtxtHandle phContext); - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage( - PCtxtHandle phContext, - PSecBufferDesc pMessage, - unsigned long MessageSeqNo, - unsigned long pfQOP -); - -typedef DWORD (WINAPI *decryptMessage_fn)( - PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP); - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, // Cred to base context - PCtxtHandle phContext, // Existing context (OPT) - LPSTR pszTargetName, // Name of target - unsigned long fContextReq, // Context Requirements - unsigned long Reserved1, // Reserved, MBZ - unsigned long TargetDataRep, // Data rep of target - PSecBufferDesc pInput, // Input Buffers - unsigned long Reserved2, // Reserved, MBZ - PCtxtHandle phNewContext, // (out) New Context handle - PSecBufferDesc pOutput, // (inout) Output Buffers - unsigned long * pfContextAttr, // (out) Context attrs - PTimeStamp ptsExpiry // (out) Life span (OPT) -); - -typedef DWORD (WINAPI *initializeSecurityContext_fn)( - PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, unsigned long * pfContextAttr, PTimeStamp ptsExpiry); - -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, // Context to query - unsigned long ulAttribute, // Attribute to query - void * pBuffer // Buffer for attributes -); - -typedef DWORD (WINAPI *queryContextAttributes_fn)( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer); - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface(); - -typedef DWORD (WINAPI *initSecurityInterface_fn) (); - -/** - * Load security.dll dynamically - */ -int load_library(); - -#endif \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc deleted file mode 100755 index e7a472f6..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h deleted file mode 100755 index fb62b55d..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include -#include "nan.h" - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - NanCallback *callback; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Handle (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc deleted file mode 100755 index f27ff8f2..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc +++ /dev/null @@ -1,106 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_buffer.h" - -using namespace node; - -Persistent SecurityBuffer::constructor_template; - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size) : ObjectWrap() { - this->size = size; - this->data = calloc(size, sizeof(char)); - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size, void *data) : ObjectWrap() { - this->size = size; - this->data = data; - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::~SecurityBuffer() { - free(this->data); -} - -NAN_METHOD(SecurityBuffer::New) { - NanScope(); - SecurityBuffer *security_obj; - - if(args.Length() != 2) - return NanThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!args[0]->IsInt32()) - return NanThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!args[1]->IsInt32() && !Buffer::HasInstance(args[1])) - return NanThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - // Unpack buffer type - uint32_t buffer_type = args[0]->ToUint32()->Value(); - - // If we have an integer - if(args[1]->IsInt32()) { - security_obj = new SecurityBuffer(buffer_type, args[1]->ToUint32()->Value()); - } else { - // Get the length of the Buffer - size_t length = Buffer::Length(args[1]->ToObject()); - // Allocate space for the internal void data pointer - void *data = calloc(length, sizeof(char)); - // Write the data to out of V8 heap space - memcpy(data, Buffer::Data(args[1]->ToObject()), length); - // Create new SecurityBuffer - security_obj = new SecurityBuffer(buffer_type, length, data); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - NanReturnValue(args.This()); -} - -NAN_METHOD(SecurityBuffer::ToBuffer) { - NanScope(); - // Unpack the Security Buffer object - SecurityBuffer *security_obj = ObjectWrap::Unwrap(args.This()); - // Create a Buffer - Local buffer = NanNewBufferHandle((char *)security_obj->data, (uint32_t)security_obj->size); - // Return the buffer - NanReturnValue(buffer); -} - -void SecurityBuffer::Initialize(Handle target) { - // Grab the scope of the call from Node - NanScope(); - - // Define a new function template - Local t = NanNew(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(NanNew("SecurityBuffer")); - - // Class methods - NODE_SET_PROTOTYPE_METHOD(t, "toBuffer", ToBuffer); - - // Set persistent - NanAssignPersistent(constructor_template, t); - - // Set the symbol - target->ForceSet(NanNew("SecurityBuffer"), t->GetFunction()); -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h deleted file mode 100755 index 65b0fdd9..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef SECURITY_BUFFER_H -#define SECURITY_BUFFER_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include "nan.h" - -using namespace v8; -using namespace node; - -class SecurityBuffer : public ObjectWrap { - public: - SecurityBuffer(uint32_t security_type, size_t size); - SecurityBuffer(uint32_t security_type, size_t size, void *data); - ~SecurityBuffer(); - - // Internal values - void *data; - size_t size; - uint32_t security_type; - SecBuffer sec_buffer; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return NanNew(constructor_template)->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - static NAN_METHOD(ToBuffer); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - static NAN_METHOD(New); -}; - -#endif \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js deleted file mode 100755 index 4996163c..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js +++ /dev/null @@ -1,12 +0,0 @@ -var SecurityBufferNative = require('../../../build/Release/kerberos').SecurityBuffer; - -// Add some attributes -SecurityBufferNative.VERSION = 0; -SecurityBufferNative.EMPTY = 0; -SecurityBufferNative.DATA = 1; -SecurityBufferNative.TOKEN = 2; -SecurityBufferNative.PADDING = 9; -SecurityBufferNative.STREAM = 10; - -// Export the modified class -exports.SecurityBuffer = SecurityBufferNative; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc deleted file mode 100755 index e9ac9636..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc +++ /dev/null @@ -1,185 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include "security_buffer_descriptor.h" -#include "security_buffer.h" - -Persistent SecurityBufferDescriptor::constructor_template; - -SecurityBufferDescriptor::SecurityBufferDescriptor() : ObjectWrap() { -} - -SecurityBufferDescriptor::SecurityBufferDescriptor(const Persistent& arrayObjectPersistent) : ObjectWrap() { - SecurityBuffer *security_obj = NULL; - // Get the Local value - Local arrayObject = NanNew(arrayObjectPersistent); - - // Safe reference to array - this->arrayObject = arrayObject; - - // Unpack the array and ensure we have a valid descriptor - this->secBufferDesc.cBuffers = arrayObject->Length(); - this->secBufferDesc.ulVersion = SECBUFFER_VERSION; - - if(arrayObject->Length() == 1) { - // Unwrap the buffer - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - // Assign the buffer - this->secBufferDesc.pBuffers = &security_obj->sec_buffer; - } else { - this->secBufferDesc.pBuffers = new SecBuffer[arrayObject->Length()]; - this->secBufferDesc.cBuffers = arrayObject->Length(); - - // Assign the buffers - for(uint32_t i = 0; i < arrayObject->Length(); i++) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(i)->ToObject()); - this->secBufferDesc.pBuffers[i].BufferType = security_obj->sec_buffer.BufferType; - this->secBufferDesc.pBuffers[i].pvBuffer = security_obj->sec_buffer.pvBuffer; - this->secBufferDesc.pBuffers[i].cbBuffer = security_obj->sec_buffer.cbBuffer; - } - } -} - -SecurityBufferDescriptor::~SecurityBufferDescriptor() { -} - -size_t SecurityBufferDescriptor::bufferSize() { - SecurityBuffer *security_obj = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - return security_obj->size; - } else { - int bytesToAllocate = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - bytesToAllocate += this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return total size - return bytesToAllocate; - } -} - -char *SecurityBufferDescriptor::toBuffer() { - SecurityBuffer *security_obj = NULL; - char *data = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - data = (char *)malloc(security_obj->size * sizeof(char)); - memcpy(data, security_obj->data, security_obj->size); - } else { - size_t bytesToAllocate = this->bufferSize(); - char *data = (char *)calloc(bytesToAllocate, sizeof(char)); - int offset = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - memcpy((data + offset), this->secBufferDesc.pBuffers[i].pvBuffer, this->secBufferDesc.pBuffers[i].cbBuffer); - offset +=this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return the data - return data; - } - - return data; -} - -NAN_METHOD(SecurityBufferDescriptor::New) { - NanScope(); - SecurityBufferDescriptor *security_obj; - Persistent arrayObject; - - if(args.Length() != 1) - return NanThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(!args[0]->IsInt32() && !args[0]->IsArray()) - return NanThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(args[0]->IsArray()) { - Handle array = Handle::Cast(args[0]); - // Iterate over all items and ensure we the right type - for(uint32_t i = 0; i < array->Length(); i++) { - if(!SecurityBuffer::HasInstance(array->Get(i))) { - return NanThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - } - } - } - - // We have a single integer - if(args[0]->IsInt32()) { - // Create new SecurityBuffer instance - Local argv[] = {NanNew(0x02), args[0]}; - Handle security_buffer = NanNew(SecurityBuffer::constructor_template)->GetFunction()->NewInstance(2, argv); - // Create a new array - Local array = NanNew(1); - // Set the first value - array->Set(0, security_buffer); - - // Create persistent handle - Persistent persistenHandler; - NanAssignPersistent(persistenHandler, array); - - // Create descriptor - security_obj = new SecurityBufferDescriptor(persistenHandler); - } else { - // Create a persistent handler - Persistent persistenHandler; - NanAssignPersistent(persistenHandler, Handle::Cast(args[0])); - // Create a descriptor - security_obj = new SecurityBufferDescriptor(persistenHandler); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - NanReturnValue(args.This()); -} - -NAN_METHOD(SecurityBufferDescriptor::ToBuffer) { - NanScope(); - - // Unpack the Security Buffer object - SecurityBufferDescriptor *security_obj = ObjectWrap::Unwrap(args.This()); - - // Get the buffer - char *buffer_data = security_obj->toBuffer(); - size_t buffer_size = security_obj->bufferSize(); - - // Create a Buffer - Local buffer = NanNewBufferHandle(buffer_data, (uint32_t)buffer_size); - - // Return the buffer - NanReturnValue(buffer); -} - -void SecurityBufferDescriptor::Initialize(Handle target) { - // Grab the scope of the call from Node - NanScope(); - - // Define a new function template - Local t = NanNew(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(NanNew("SecurityBufferDescriptor")); - - // Class methods - NODE_SET_PROTOTYPE_METHOD(t, "toBuffer", ToBuffer); - - // Set persistent - NanAssignPersistent(constructor_template, t); - - // Set the symbol - target->ForceSet(NanNew("SecurityBufferDescriptor"), t->GetFunction()); -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h deleted file mode 100755 index c4d98e45..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef SECURITY_BUFFER_DESCRIPTOR_H -#define SECURITY_BUFFER_DESCRIPTOR_H - -#include -#include -#include - -#include -#include -#include -#include "nan.h" - -using namespace v8; -using namespace node; - -class SecurityBufferDescriptor : public ObjectWrap { - public: - Local arrayObject; - SecBufferDesc secBufferDesc; - - SecurityBufferDescriptor(); - SecurityBufferDescriptor(const Persistent& arrayObjectPersistent); - ~SecurityBufferDescriptor(); - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return NanNew(constructor_template)->HasInstance(obj); - }; - - char *toBuffer(); - size_t bufferSize(); - - // Functions available from V8 - static void Initialize(Handle target); - static NAN_METHOD(ToBuffer); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - static NAN_METHOD(New); -}; - -#endif \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js deleted file mode 100755 index 9421392e..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityBufferDescriptorNative = require('../../../build/Release/kerberos').SecurityBufferDescriptor; -// Export the modified class -exports.SecurityBufferDescriptor = SecurityBufferDescriptorNative; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc deleted file mode 100755 index cd473203..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc +++ /dev/null @@ -1,869 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_context.h" -#include "security_buffer_descriptor.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -static void After(uv_work_t* work_req) { - // Grab the scope of the call from Node - NanScope(); - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - Local err = v8::Exception::Error(NanNew(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NanNew("code"), NanNew(worker->error_code)); - Local args[2] = { err, NanNull() }; - // Execute the error - v8::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(args), args); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - Handle result = worker->mapper(worker); - // Set up the callback with a null first - Handle args[2] = { NanNull(), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(args), args); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - delete worker->callback; - delete worker; -} - -Persistent SecurityContext::constructor_template; - -SecurityContext::SecurityContext() : ObjectWrap() { -} - -SecurityContext::~SecurityContext() { - if(this->hasContext) { - _sspi_DeleteSecurityContext(&this->m_Context); - } -} - -NAN_METHOD(SecurityContext::New) { - NanScope(); - - PSecurityFunctionTable pSecurityInterface = NULL; - DWORD dwNumOfPkgs; - SECURITY_STATUS status; - - // Create code object - SecurityContext *security_obj = new SecurityContext(); - // Get security table interface - pSecurityInterface = _ssip_InitSecurityInterface(); - // Call the security interface - status = (*pSecurityInterface->EnumerateSecurityPackages)( - &dwNumOfPkgs, - &security_obj->m_PkgInfo); - if(status != SEC_E_OK) { - printf(TEXT("Failed in retrieving security packages, Error: %x"), GetLastError()); - return NanThrowError("Failed in retrieving security packages"); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - NanReturnValue(args.This()); -} - -// -// Async InitializeContext -// -typedef struct SecurityContextStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStaticInitializeCall; - -static void _initializeContext(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - BYTE *out_bound_data_str = NULL; - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)worker->parameters; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = call->context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &call->context->security_credentials->m_Credentials - , NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length > 0 ? &ibd : NULL - , 0 - , &call->context->m_Context - , &obd - , &call->context->CtxtAttr - , &call->context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - call->context->hasContext = true; - call->context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - - // Set the context - worker->return_code = status; - worker->return_value = call->context; - } else if(status == SEC_E_INSUFFICIENT_MEMORY) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_INSUFFICIENT_MEMORY There is not enough memory available to complete the requested action."; - } else if(status == SEC_E_INTERNAL_ERROR) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_INTERNAL_ERROR An error occurred that did not map to an SSPI error code."; - } else if(status == SEC_E_INVALID_HANDLE) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_INVALID_HANDLE The handle passed to the function is not valid."; - } else if(status == SEC_E_INVALID_TOKEN) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_INVALID_TOKEN The error is due to a malformed input token, such as a token corrupted in transit, a token of incorrect size, or a token passed into the wrong security package. Passing a token to the wrong package can happen if the client and server did not negotiate the proper security package."; - } else if(status == SEC_E_LOGON_DENIED) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_LOGON_DENIED The logon failed."; - } else if(status == SEC_E_NO_AUTHENTICATING_AUTHORITY) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_NO_AUTHENTICATING_AUTHORITY No authority could be contacted for authentication. The domain name of the authenticating party could be wrong, the domain could be unreachable, or there might have been a trust relationship failure."; - } else if(status == SEC_E_NO_CREDENTIALS) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_NO_CREDENTIALS No credentials are available in the security package."; - } else if(status == SEC_E_TARGET_UNKNOWN) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_TARGET_UNKNOWN The target was not recognized."; - } else if(status == SEC_E_UNSUPPORTED_FUNCTION) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_UNSUPPORTED_FUNCTION A context attribute flag that is not valid (ISC_REQ_DELEGATE or ISC_REQ_PROMPT_FOR_CREDS) was specified in the fContextReq parameter."; - } else if(status == SEC_E_WRONG_PRINCIPAL) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_WRONG_PRINCIPAL The principal that received the authentication request is not the same as the one passed into the pszTargetName parameter. This indicates a failure in mutual authentication."; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Handle _map_initializeContext(Worker *worker) { - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return NanObjectWrapHandle(context); -} - -NAN_METHOD(SecurityContext::InitializeContext) { - NanScope(); - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - // Store reference to security credentials - SecurityCredentials *security_credentials = NULL; - - // We need 3 parameters - if(args.Length() != 4) - return NanThrowError("Initialize must be called with [credential:SecurityCredential, servicePrincipalName:string, input:string, callback:function]"); - - // First parameter must be an instance of SecurityCredentials - if(!SecurityCredentials::HasInstance(args[0])) - return NanThrowError("First parameter for Initialize must be an instance of SecurityCredentials"); - - // Second parameter must be a string - if(!args[1]->IsString()) - return NanThrowError("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsString()) - return NanThrowError("Second parameter for Initialize must be a string"); - - // Third parameter must be a callback - if(!args[3]->IsFunction()) - return NanThrowError("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = args[1]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[2]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free original allocation - free(input_str); - } - - // Unpack the Security credentials - security_credentials = ObjectWrap::Unwrap(args[0]->ToObject()); - // Create Security context instance - Local security_context_value = NanNew(constructor_template)->GetFunction()->NewInstance(); - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(security_context_value); - // Add a reference to the security_credentials - security_context->security_credentials = security_credentials; - - // Build the call function - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)calloc(1, sizeof(SecurityContextStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(args[3]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new NanCallback(callback); - worker->parameters = call; - worker->execute = _initializeContext; - worker->mapper = _map_initializeContext; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - NanReturnValue(NanUndefined()); -} - -NAN_GETTER(SecurityContext::PayloadGetter) { - NanScope(); - // Unpack the context object - SecurityContext *context = ObjectWrap::Unwrap(args.This()); - // Return the low bits - NanReturnValue(NanNew(context->payload)); -} - -NAN_GETTER(SecurityContext::HasContextGetter) { - NanScope(); - // Unpack the context object - SecurityContext *context = ObjectWrap::Unwrap(args.This()); - // Return the low bits - NanReturnValue(NanNew(context->hasContext)); -} - -// -// Async InitializeContextStep -// -typedef struct SecurityContextStepStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStepStaticInitializeCall; - -static void _initializeContextStep(Worker *worker) { - // Outbound data array - BYTE *out_bound_data_str = NULL; - // Status of operation - SECURITY_STATUS status; - // Unpack data - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)worker->parameters; - SecurityContext *context = call->context; - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &context->security_credentials->m_Credentials - , context->hasContext == true ? &context->m_Context : NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length ? &ibd : NULL - , 0 - , &context->m_Context - , &obd - , &context->CtxtAttr - , &context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - // Set the new payload - if(context->payload != NULL) free(context->payload); - context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Handle _map_initializeContextStep(Worker *worker) { - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return NanObjectWrapHandle(context); -} - -NAN_METHOD(SecurityContext::InitalizeStep) { - NanScope(); - - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - - // We need 3 parameters - if(args.Length() != 3) - return NanThrowError("Initialize must be called with [servicePrincipalName:string, input:string, callback:function]"); - - // Second parameter must be a string - if(!args[0]->IsString()) - return NanThrowError("First parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[1]->IsString()) - return NanThrowError("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsFunction()) - return NanThrowError("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = args[0]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[1]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free input string - free(input_str); - } - - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Create call structure - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)calloc(1, sizeof(SecurityContextStepStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new NanCallback(callback); - worker->parameters = call; - worker->execute = _initializeContextStep; - worker->mapper = _map_initializeContextStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - NanReturnValue(NanUndefined()); -} - -// -// Async EncryptMessage -// -typedef struct SecurityContextEncryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; - unsigned long flags; -} SecurityContextEncryptMessageCall; - -static void _encryptMessage(Worker *worker) { - SECURITY_STATUS status; - // Unpack call - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)worker->parameters; - // Unpack the security context - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_EncryptMessage( - &context->m_Context - , call->flags - , &descriptor->secBufferDesc - , 0 - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set result - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_encryptMessage(Worker *worker) { - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return NanObjectWrapHandle(context); -} - -NAN_METHOD(SecurityContext::EncryptMessage) { - NanScope(); - - if(args.Length() != 3) - return NanThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return NanThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!args[1]->IsUint32()) - return NanThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!args[2]->IsFunction()) - return NanThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Create call structure - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)calloc(1, sizeof(SecurityContextEncryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - call->flags = (unsigned long)args[1]->ToInteger()->Value(); - - // Callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new NanCallback(callback); - worker->parameters = call; - worker->execute = _encryptMessage; - worker->mapper = _map_encryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - NanReturnValue(NanUndefined()); -} - -// -// Async DecryptMessage -// -typedef struct SecurityContextDecryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; -} SecurityContextDecryptMessageCall; - -static void _decryptMessage(Worker *worker) { - unsigned long quality = 0; - SECURITY_STATUS status; - - // Unpack parameters - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)worker->parameters; - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_DecryptMessage( - &context->m_Context - , &descriptor->secBufferDesc - , 0 - , (unsigned long)&quality - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set return values - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_decryptMessage(Worker *worker) { - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return NanObjectWrapHandle(context); -} - -NAN_METHOD(SecurityContext::DecryptMessage) { - NanScope(); - - if(args.Length() != 2) - return NanThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return NanThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!args[1]->IsFunction()) - return NanThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - // Create call structure - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)calloc(1, sizeof(SecurityContextDecryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - - // Callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new NanCallback(callback); - worker->parameters = call; - worker->execute = _decryptMessage; - worker->mapper = _map_decryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - NanReturnValue(NanUndefined()); -} - -// -// Async QueryContextAttributes -// -typedef struct SecurityContextQueryContextAttributesCall { - SecurityContext *context; - uint32_t attribute; -} SecurityContextQueryContextAttributesCall; - -static void _queryContextAttributes(Worker *worker) { - SECURITY_STATUS status; - - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - - // Allocate some space - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)calloc(1, sizeof(SecPkgContext_Sizes)); - // Let's grab the query context attribute - status = _sspi_QueryContextAttributes( - &call->context->m_Context, - call->attribute, - sizes - ); - - if(status == SEC_E_OK) { - worker->return_code = status; - worker->return_value = sizes; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_queryContextAttributes(Worker *worker) { - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - // Unpack the attribute - uint32_t attribute = call->attribute; - - // Convert data - if(attribute == SECPKG_ATTR_SIZES) { - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)worker->return_value; - // Create object - Local value = NanNew(); - value->Set(NanNew("maxToken"), NanNew(uint32_t(sizes->cbMaxToken))); - value->Set(NanNew("maxSignature"), NanNew(uint32_t(sizes->cbMaxSignature))); - value->Set(NanNew("blockSize"), NanNew(uint32_t(sizes->cbBlockSize))); - value->Set(NanNew("securityTrailer"), NanNew(uint32_t(sizes->cbSecurityTrailer))); - return value; - } - - // Return the value - return NanNull(); -} - -NAN_METHOD(SecurityContext::QueryContextAttributes) { - NanScope(); - - if(args.Length() != 2) - return NanThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - if(!args[0]->IsInt32()) - return NanThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - if(!args[1]->IsFunction()) - return NanThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the int value - uint32_t attribute = args[0]->ToInt32()->Value(); - - // Check that we have a supported attribute - if(attribute != SECPKG_ATTR_SIZES) - return NanThrowError("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); - - // Create call structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)calloc(1, sizeof(SecurityContextQueryContextAttributesCall)); - call->attribute = attribute; - call->context = security_context; - - // Callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new NanCallback(callback); - worker->parameters = call; - worker->execute = _queryContextAttributes; - worker->mapper = _map_queryContextAttributes; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - NanReturnValue(NanUndefined()); -} - -void SecurityContext::Initialize(Handle target) { - // Grab the scope of the call from Node - NanScope(); - - // Define a new function template - Local t = NanNew(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(NanNew("SecurityContext")); - - // Class methods - NODE_SET_METHOD(t, "initialize", InitializeContext); - - // Set up method for the instance - NODE_SET_PROTOTYPE_METHOD(t, "initialize", InitalizeStep); - NODE_SET_PROTOTYPE_METHOD(t, "decryptMessage", DecryptMessage); - NODE_SET_PROTOTYPE_METHOD(t, "queryContextAttributes", QueryContextAttributes); - NODE_SET_PROTOTYPE_METHOD(t, "encryptMessage", EncryptMessage); - - // Get prototype - Local proto = t->PrototypeTemplate(); - - // Getter for the response - proto->SetAccessor(NanNew("payload"), SecurityContext::PayloadGetter); - proto->SetAccessor(NanNew("hasContext"), SecurityContext::HasContextGetter); - - // Set persistent - NanAssignPersistent(constructor_template, t); - - // Set the symbol - target->ForceSet(NanNew("SecurityContext"), t->GetFunction()); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessageSync (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - } - - return pszName; -} - diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h deleted file mode 100755 index fee23916..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef SECURITY_CONTEXT_H -#define SECURITY_CONTEXT_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include -#include "security_credentials.h" -#include "../worker.h" -#include "nan.h" - -extern "C" { - #include "../kerberos_sspi.h" - #include "../base64.h" -} - -using namespace v8; -using namespace node; - -class SecurityContext : public ObjectWrap { - public: - SecurityContext(); - ~SecurityContext(); - - // Security info package - PSecPkgInfo m_PkgInfo; - // Do we have a context - bool hasContext; - // Reference to security credentials - SecurityCredentials *security_credentials; - // Security context - CtxtHandle m_Context; - // Attributes - DWORD CtxtAttr; - // Expiry time for ticket - TimeStamp Expiration; - // Payload - char *payload; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return NanNew(constructor_template)->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - static NAN_METHOD(InitializeContext); - static NAN_METHOD(InitalizeStep); - static NAN_METHOD(DecryptMessage); - static NAN_METHOD(QueryContextAttributes); - static NAN_METHOD(EncryptMessage); - - // Payload getter - static NAN_GETTER(PayloadGetter); - // hasContext getter - static NAN_GETTER(HasContextGetter); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - // Create a new instance - static NAN_METHOD(New); -}; - -#endif diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js deleted file mode 100755 index ef04e927..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityContextNative = require('../../../build/Release/kerberos').SecurityContext; -// Export the modified class -exports.SecurityContext = SecurityContextNative; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc deleted file mode 100755 index fc2a3d85..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc +++ /dev/null @@ -1,351 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_credentials.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -Persistent SecurityCredentials::constructor_template; - -SecurityCredentials::SecurityCredentials() : ObjectWrap() { -} - -SecurityCredentials::~SecurityCredentials() { -} - -NAN_METHOD(SecurityCredentials::New) { - NanScope(); - // Create security credentials instance - SecurityCredentials *security_credentials = new SecurityCredentials(); - // Wrap it - security_credentials->Wrap(args.This()); - // Return the object - NanReturnValue(args.This()); -} - -// Call structs -typedef struct SecurityCredentialCall { - char *package_str; - char *username_str; - char *password_str; - char *domain_str; - SecurityCredentials *credentials; -} SecurityCredentialCall; - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authSSPIAquire(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - - // Unpack data - SecurityCredentialCall *call = (SecurityCredentialCall *)worker->parameters; - - // // Unwrap the credentials - // SecurityCredentials *security_credentials = (SecurityCredentials *)call->credentials; - SecurityCredentials *security_credentials = new SecurityCredentials(); - - // If we have domain string - if(call->domain_str != NULL) { - security_credentials->m_Identity.Domain = USTR(_tcsdup(call->domain_str)); - security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(call->domain_str); - } else { - security_credentials->m_Identity.Domain = NULL; - security_credentials->m_Identity.DomainLength = 0; - } - - // Set up the user - security_credentials->m_Identity.User = USTR(_tcsdup(call->username_str)); - security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(call->username_str); - - // If we have a password string - if(call->password_str != NULL) { - // Set up the password - security_credentials->m_Identity.Password = USTR(_tcsdup(call->password_str)); - security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(call->password_str); - } - - #ifdef _UNICODE - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; - #else - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; - #endif - - // Attempt to acquire credentials - status = _sspi_AcquireCredentialsHandle( - NULL, - call->package_str, - SECPKG_CRED_OUTBOUND, - NULL, - call->password_str != NULL ? &security_credentials->m_Identity : NULL, - NULL, NULL, - &security_credentials->m_Credentials, - &security_credentials->Expiration - ); - - // We have an error - if(status != SEC_E_OK) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } else { - worker->return_code = status; - worker->return_value = security_credentials; - } - - // Free up parameter structure - if(call->package_str != NULL) free(call->package_str); - if(call->domain_str != NULL) free(call->domain_str); - if(call->password_str != NULL) free(call->password_str); - if(call->username_str != NULL) free(call->username_str); - free(call); -} - -static Handle _map_authSSPIAquire(Worker *worker) { - return NanNull(); -} - -NAN_METHOD(SecurityCredentials::Aquire) { - NanScope(); - - char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; - // Unpack the variables - if(args.Length() != 2 && args.Length() != 3 && args.Length() != 4 && args.Length() != 5) - return NanThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!args[0]->IsString()) - return NanThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!args[1]->IsString()) - return NanThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 3 && (!args[2]->IsString() && !args[2]->IsFunction())) - return NanThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 4 && (!args[3]->IsString() && !args[3]->IsUndefined() && !args[3]->IsNull()) && !args[3]->IsFunction()) - return NanThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 5 && !args[4]->IsFunction()) - return NanThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - Local callbackHandle; - - // Figure out which parameter is the callback - if(args.Length() == 5) { - callbackHandle = Local::Cast(args[4]); - } else if(args.Length() == 4) { - callbackHandle = Local::Cast(args[3]); - } else if(args.Length() == 3) { - callbackHandle = Local::Cast(args[2]); - } - - // Unpack the package - Local package = args[0]->ToString(); - package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); - package->WriteUtf8(package_str); - - // Unpack the user name - Local username = args[1]->ToString(); - username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); - username->WriteUtf8(username_str); - - // If we have a password - if(args.Length() == 3 || args.Length() == 4 || args.Length() == 5) { - Local password = args[2]->ToString(); - password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); - password->WriteUtf8(password_str); - } - - // If we have a domain - if((args.Length() == 4 || args.Length() == 5) && args[3]->IsString()) { - Local domain = args[3]->ToString(); - domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); - domain->WriteUtf8(domain_str); - } - - // Allocate call structure - SecurityCredentialCall *call = (SecurityCredentialCall *)calloc(1, sizeof(SecurityCredentialCall)); - call->domain_str = domain_str; - call->package_str = package_str; - call->password_str = password_str; - call->username_str = username_str; - - // Unpack the callback - NanCallback *callback = new NanCallback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authSSPIAquire; - worker->mapper = _map_authSSPIAquire; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, SecurityCredentials::Process, (uv_after_work_cb)SecurityCredentials::After); - - // Return no value as it's callback based - NanReturnValue(NanUndefined()); -} - -void SecurityCredentials::Initialize(Handle target) { - // Grab the scope of the call from Node - NanScope(); - - // Define a new function template - Local t = NanNew(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(NanNew("SecurityCredentials")); - - // Class methods - NODE_SET_METHOD(t, "aquire", Aquire); - - // Set persistent - NanAssignPersistent(constructor_template, t); - - // Set the symbol - target->ForceSet(NanNew("SecurityCredentials"), t->GetFunction()); - - // Attempt to load the security.dll library - load_library(); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessage (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - - } - - return pszName; -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void SecurityCredentials::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void SecurityCredentials::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - NanScope(); - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - Local err = v8::Exception::Error(NanNew(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NanNew("code"), NanNew(worker->error_code)); - Local args[2] = { err, NanNull() }; - // Execute the error - v8::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(args), args); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - SecurityCredentials *return_value = (SecurityCredentials *)worker->return_value; - // Create a new instance - Local result = NanNew(constructor_template)->GetFunction()->NewInstance(); - // Unwrap the credentials - SecurityCredentials *security_credentials = ObjectWrap::Unwrap(result); - // Set the values - security_credentials->m_Identity = return_value->m_Identity; - security_credentials->m_Credentials = return_value->m_Credentials; - security_credentials->Expiration = return_value->Expiration; - // Set up the callback with a null first - Handle args[2] = { NanNull(), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(args), args); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - delete worker->callback; - delete worker; -} - diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h deleted file mode 100755 index b026070f..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef SECURITY_CREDENTIALS_H -#define SECURITY_CREDENTIALS_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include -#include "nan.h" -#include "../worker.h" -#include - -extern "C" { - #include "../kerberos_sspi.h" -} - -// SEC_WINNT_AUTH_IDENTITY makes it unusually hard -// to compile for both Unicode and ansi, so I use this macro: -#ifdef _UNICODE -#define USTR(str) (str) -#else -#define USTR(str) ((unsigned char*)(str)) -#endif - -using namespace v8; -using namespace node; - -class SecurityCredentials : public ObjectWrap { - public: - SecurityCredentials(); - ~SecurityCredentials(); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return NanNew(constructor_template)->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - static NAN_METHOD(Aquire); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - // Create a new instance - static NAN_METHOD(New); - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js deleted file mode 100755 index 4215c927..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js +++ /dev/null @@ -1,22 +0,0 @@ -var SecurityCredentialsNative = require('../../../build/Release/kerberos').SecurityCredentials; - -// Add simple kebros helper -SecurityCredentialsNative.aquire_kerberos = function(username, password, domain, callback) { - if(typeof password == 'function') { - callback = password; - password = null; - } else if(typeof domain == 'function') { - callback = domain; - domain = null; - } - - // We are going to use the async version - if(typeof callback == 'function') { - return SecurityCredentialsNative.aquire('Kerberos', username, password, domain, callback); - } else { - return SecurityCredentialsNative.aquireSync('Kerberos', username, password, domain); - } -} - -// Export the modified class -exports.SecurityCredentials = SecurityCredentialsNative; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/worker.cc b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/worker.cc deleted file mode 100755 index e7a472f6..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/worker.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/worker.h deleted file mode 100755 index cbc7f6a4..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/lib/worker.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - NanCallback *callback; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Handle (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/.dntrc b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/.dntrc deleted file mode 100755 index 47971da6..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/.dntrc +++ /dev/null @@ -1,30 +0,0 @@ -## DNT config file -## see https://github.com/rvagg/dnt - -NODE_VERSIONS="\ - master \ - v0.11.13 \ - v0.10.30 \ - v0.10.29 \ - v0.10.28 \ - v0.10.26 \ - v0.10.25 \ - v0.10.24 \ - v0.10.23 \ - v0.10.22 \ - v0.10.21 \ - v0.10.20 \ - v0.10.19 \ - v0.8.28 \ - v0.8.27 \ - v0.8.26 \ - v0.8.24 \ -" -OUTPUT_PREFIX="nan-" -TEST_CMD=" \ - cd /dnt/ && \ - npm install && \ - node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \ - node_modules/.bin/tap --gc test/js/*-test.js \ -" - diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/CHANGELOG.md b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/CHANGELOG.md deleted file mode 100755 index de0ac02a..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/CHANGELOG.md +++ /dev/null @@ -1,265 +0,0 @@ -# NAN ChangeLog - -**Version 1.6.2: current Node unstable: 0.11.16, Node stable: 0.10.36, io.js: 1.1.0** - -### 1.6.2 Feb 6 2015 - - - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 - -### 1.6.1 Jan 23 2015 - - - Build: version bump - -### 1.5.3 Jan 23 2015 - - - Build: repackage - -### 1.6.0 Jan 23 2015 - - - Deprecated `NanNewContextHandle` in favor of `NanNew` 49259af - - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 - - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 - -### 1.5.2 Jan 23 2015 - - - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 - - Bugfix: Readded missing String constructors 18d828f - - Bugfix: Add overload handling NanNew(..) 5ef813b - - Bugfix: Fix uv_work_cb versioning 997e4ae - - Bugfix: Add function factory and test 4eca89c - - Bugfix: Add object template factory and test cdcb951 - - Correctness: Lifted an io.js related typedef c9490be - - Correctness: Make explicit downcasts of String lengths 00074e6 - - Windows: Limit the scope of disabled warning C4530 83d7deb - -### 1.5.1 Jan 15 2015 - - - Build: version bump - -### 1.4.3 Jan 15 2015 - - - Build: version bump - -### 1.4.2 Jan 15 2015 - - - Feature: Support io.js 0dbc5e8 - -### 1.5.0 Jan 14 2015 - - - Feature: Support io.js b003843 - - Correctness: Improved NanNew internals 9cd4f6a - - Feature: Implement progress to NanAsyncWorker 8d6a160 - -### 1.4.1 Nov 8 2014 - - - Bugfix: Handle DEBUG definition correctly - - Bugfix: Accept int as Boolean - -### 1.4.0 Nov 1 2014 - - - Feature: Added NAN_GC_CALLBACK 6a5c245 - - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 - - Correctness: Added constness to references in NanHasInstance 02c61cd - - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 - - Windoze: Shut Visual Studio up when compiling 8d558c1 - - License: Switch to plain MIT from custom hacked MIT license 11de983 - - Build: Added test target to Makefile e232e46 - - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 - - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 - - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 - -### 1.3.0 Aug 2 2014 - - - Added NanNew(std::string) - - Added NanNew(std::string&) - - Added NanAsciiString helper class - - Added NanUtf8String helper class - - Added NanUcs2String helper class - - Deprecated NanRawString() - - Deprecated NanCString() - - Added NanGetIsolateData(v8::Isolate *isolate) - - Added NanMakeCallback(v8::Handle target, v8::Handle func, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, v8::Handle symbol, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, const char* method, int argc, v8::Handle* argv) - - Added NanSetTemplate(v8::Handle templ, v8::Handle name , v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetPrototypeTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetInstanceTemplate(v8::Local templ, const char *name, v8::Handle value) - - Added NanSetInstanceTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - -### 1.2.0 Jun 5 2014 - - - Add NanSetPrototypeTemplate - - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, - introduced _NanWeakCallbackDispatcher - - Removed -Wno-unused-local-typedefs from test builds - - Made test builds Windows compatible ('Sleep()') - -### 1.1.2 May 28 2014 - - - Release to fix more stuff-ups in 1.1.1 - -### 1.1.1 May 28 2014 - - - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 - -### 1.1.0 May 25 2014 - - - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead - - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), - (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, - v8::String::ExternalAsciiStringResource* - - Deprecate NanSymbol() - - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker - -### 1.0.0 May 4 2014 - - - Heavy API changes for V8 3.25 / Node 0.11.13 - - Use cpplint.py - - Removed NanInitPersistent - - Removed NanPersistentToLocal - - Removed NanFromV8String - - Removed NanMakeWeak - - Removed NanNewLocal - - Removed NAN_WEAK_CALLBACK_OBJECT - - Removed NAN_WEAK_CALLBACK_DATA - - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions - - Introduce NanUndefined, NanNull, NanTrue and NanFalse - - Introduce NanEscapableScope and NanEscapeScope - - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) - - Introduce NanMakeCallback for node::MakeCallback - - Introduce NanSetTemplate - - Introduce NanGetCurrentContext - - Introduce NanCompileScript and NanRunScript - - Introduce NanAdjustExternalMemory - - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback - - Introduce NanGetHeapStatistics - - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() - -### 0.8.0 Jan 9 2014 - - - NanDispose -> NanDisposePersistent, deprecate NanDispose - - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() - -### 0.7.1 Jan 9 2014 - - - Fixes to work against debug builds of Node - - Safer NanPersistentToLocal (avoid reinterpret_cast) - - Speed up common NanRawString case by only extracting flattened string when necessary - -### 0.7.0 Dec 17 2013 - - - New no-arg form of NanCallback() constructor. - - NanCallback#Call takes Handle rather than Local - - Removed deprecated NanCallback#Run method, use NanCallback#Call instead - - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS - - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() - - Introduce NanRawString() for char* (or appropriate void*) from v8::String - (replacement for NanFromV8String) - - Introduce NanCString() for null-terminated char* from v8::String - -### 0.6.0 Nov 21 2013 - - - Introduce NanNewLocal(v8::Handle value) for use in place of - v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 - -### 0.5.2 Nov 16 2013 - - - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public - -### 0.5.1 Nov 12 2013 - - - Use node::MakeCallback() instead of direct v8::Function::Call() - -### 0.5.0 Nov 11 2013 - - - Added @TooTallNate as collaborator - - New, much simpler, "include_dirs" for binding.gyp - - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros - -### 0.4.4 Nov 2 2013 - - - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ - -### 0.4.3 Nov 2 2013 - - - Include node_object_wrap.h, removed from node.h for Node 0.11.8. - -### 0.4.2 Nov 2 2013 - - - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for - Node 0.11.8 release. - -### 0.4.1 Sep 16 2013 - - - Added explicit `#include ` as it was removed from node.h for v0.11.8 - -### 0.4.0 Sep 2 2013 - - - Added NAN_INLINE and NAN_DEPRECATED and made use of them - - Added NanError, NanTypeError and NanRangeError - - Cleaned up code - -### 0.3.2 Aug 30 2013 - - - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent - in NanAsyncWorker - -### 0.3.1 Aug 20 2013 - - - fix "not all control paths return a value" compile warning on some platforms - -### 0.3.0 Aug 19 2013 - - - Made NAN work with NPM - - Lots of fixes to NanFromV8String, pulling in features from new Node core - - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API - - Added optional error number argument for NanThrowError() - - Added NanInitPersistent() - - Added NanReturnNull() and NanReturnEmptyString() - - Added NanLocker and NanUnlocker - - Added missing scopes - - Made sure to clear disposed Persistent handles - - Changed NanAsyncWorker to allocate error messages on the heap - - Changed NanThrowError(Local) to NanThrowError(Handle) - - Fixed leak in NanAsyncWorker when errmsg is used - -### 0.2.2 Aug 5 2013 - - - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() - -### 0.2.1 Aug 5 2013 - - - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for - NanFromV8String() - -### 0.2.0 Aug 5 2013 - - - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, - NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY - - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, - _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, - _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, - _NAN_PROPERTY_QUERY_ARGS - - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer - - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, - NAN_WEAK_CALLBACK_DATA, NanMakeWeak - - Renamed THROW_ERROR to _NAN_THROW_ERROR - - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) - - Added NanBufferUse(char*, uint32_t) - - Added NanNewContextHandle(v8::ExtensionConfiguration*, - v8::Handle, v8::Handle) - - Fixed broken NanCallback#GetFunction() - - Added optional encoding and size arguments to NanFromV8String() - - Added NanGetPointerSafe() and NanSetPointerSafe() - - Added initial test suite (to be expanded) - - Allow NanUInt32OptionValue to convert any Number object - -### 0.1.0 Jul 21 2013 - - - Added `NAN_GETTER`, `NAN_SETTER` - - Added `NanThrowError` with single Local argument - - Added `NanNewBufferHandle` with single uint32_t argument - - Added `NanHasInstance(Persistent&, Handle)` - - Added `Local NanCallback#GetFunction()` - - Added `NanCallback#Call(int, Local[])` - - Deprecated `NanCallback#Run(int, Local[])` in favour of Call diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/LICENSE.md b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/LICENSE.md deleted file mode 100755 index 95c2eb5f..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -The MIT License (MIT) -===================== - -Copyright (c) 2015 NAN contributors ------------------------------------ - -*NAN contributors listed at * - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/appveyor.yml b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/appveyor.yml deleted file mode 100755 index 17771078..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/appveyor.yml +++ /dev/null @@ -1,37 +0,0 @@ -# http://www.appveyor.com/docs/appveyor-yml - -# Test against these versions of Io.js and Node.js. -environment: - matrix: - # node.js - - nodejs_version: "0.8" - - nodejs_version: "0.10" - - nodejs_version: "0.11" - # io.js - - nodejs_version: "1" - -# Install scripts. (runs after repo cloning) -install: - # Get the latest stable version of Node 0.STABLE.latest - - ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version} - - ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)} - - IF NOT %nodejs_version% == 1 npm -g install npm - - IF NOT %nodejs_version% == 1 set PATH=%APPDATA%\npm;%PATH% - # Typical npm stuff. - - npm install - - IF %nodejs_version% == 0.8 node node_modules\node-gyp\bin\node-gyp.js rebuild --directory test - - IF NOT %nodejs_version% == 0.8 npm run rebuild-tests - -# Post-install test scripts. -test_script: - # Output useful info for debugging. - - node --version - - npm --version - # run tests - - npm test - -# Don't actually build. -build: off - -# Set build version format here instead of in the admin panel. -version: "{build}" diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/include_dirs.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/include_dirs.js deleted file mode 100755 index 4f1dfb41..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/include_dirs.js +++ /dev/null @@ -1 +0,0 @@ -console.log(require('path').relative('.', __dirname)); diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan.h deleted file mode 100755 index e95a3b3e..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan.h +++ /dev/null @@ -1,2174 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2015 NAN contributors: - * - Rod Vagg - * - Benjamin Byholm - * - Trevor Norris - * - Nathan Rajlich - * - Brett Lawson - * - Ben Noordhuis - * - David Siegel - * - * MIT License - * - * Version 1.6.2: current Node unstable: 0.11.16, Node stable: 0.10.36, io.js: 1.1.0 - * - * See https://github.com/rvagg/nan for the latest update to this file - **********************************************************************************/ - -#ifndef NAN_H_ -#define NAN_H_ - -#include -#include -#include -#include -#include -#include -#include -#if defined(_MSC_VER) -# pragma warning( disable : 4530 ) -# include -# pragma warning( default : 4530 ) -#else -# include -#endif - -#if defined(__GNUC__) && !(defined(DEBUG) && DEBUG) -# define NAN_INLINE inline __attribute__((always_inline)) -#elif defined(_MSC_VER) && !(defined(DEBUG) && DEBUG) -# define NAN_INLINE __forceinline -#else -# define NAN_INLINE inline -#endif - -#if defined(__GNUC__) && \ - !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) -# define NAN_DEPRECATED __attribute__((deprecated)) -#elif defined(_MSC_VER) && \ - !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) -# define NAN_DEPRECATED __declspec(deprecated) -#else -# define NAN_DEPRECATED -#endif - -#if (NODE_MODULE_VERSION < 12) -typedef v8::InvocationCallback NanFunctionCallback; -typedef v8::Script NanUnboundScript; -typedef v8::Script NanBoundScript; -#else -typedef v8::FunctionCallback NanFunctionCallback; -typedef v8::UnboundScript NanUnboundScript; -typedef v8::Script NanBoundScript; -#endif - -#if (NODE_MODULE_VERSION < 42) -typedef v8::String::ExternalAsciiStringResource - NanExternalOneByteStringResource; -#else // io.js v1.0.0 -typedef v8::String::ExternalOneByteStringResource - NanExternalOneByteStringResource; -#endif - -#include "nan_new.h" // NOLINT(build/include) - -// uv helpers -#ifdef UV_VERSION_MAJOR -#ifndef UV_VERSION_PATCH -#define UV_VERSION_PATCH 0 -#endif -#define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \ - (UV_VERSION_MINOR << 8) | \ - (UV_VERSION_PATCH)) -#else -#define NAUV_UVVERSION 0x000b00 -#endif - - -#if NAUV_UVVERSION < 0x000b17 -#define NAUV_WORK_CB(func) \ - void func(uv_async_t *async, int) -#else -#define NAUV_WORK_CB(func) \ - void func(uv_async_t *async) -#endif - -// some generic helpers - -template NAN_INLINE bool NanSetPointerSafe( - T *var - , T val -) { - if (var) { - *var = val; - return true; - } else { - return false; - } -} - -template NAN_INLINE T NanGetPointerSafe( - T *var - , T fallback = reinterpret_cast(0) -) { - if (var) { - return *var; - } else { - return fallback; - } -} - -NAN_INLINE bool NanBooleanOptionValue( - v8::Local optionsObj - , v8::Handle opt, bool def -) { - if (def) { - return optionsObj.IsEmpty() - || !optionsObj->Has(opt) - || optionsObj->Get(opt)->BooleanValue(); - } else { - return !optionsObj.IsEmpty() - && optionsObj->Has(opt) - && optionsObj->Get(opt)->BooleanValue(); - } -} - -NAN_INLINE bool NanBooleanOptionValue( - v8::Local optionsObj - , v8::Handle opt -) { - return NanBooleanOptionValue(optionsObj, opt, false); -} - -NAN_INLINE uint32_t NanUInt32OptionValue( - v8::Local optionsObj - , v8::Handle opt - , uint32_t def -) { - return !optionsObj.IsEmpty() - && optionsObj->Has(opt) - && optionsObj->Get(opt)->IsNumber() - ? optionsObj->Get(opt)->Uint32Value() - : def; -} - -template -v8::Local NanNew(v8::Handle); - -template -NAN_INLINE v8::Local _NanEnsureLocal(v8::Handle val) { - return NanNew(val); -} - -template -NAN_INLINE v8::Local _NanEnsureLocal(v8::Local val) { - return val; -} - -/* io.js 1.0 */ -#if NODE_MODULE_VERSION >= 42 || NODE_VERSION_AT_LEAST(0, 11, 15) - NAN_INLINE - void NanSetCounterFunction(v8::CounterLookupCallback cb) { - v8::Isolate::GetCurrent()->SetCounterFunction(cb); - } - - NAN_INLINE - void NanSetCreateHistogramFunction(v8::CreateHistogramCallback cb) { - v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb); - } - - NAN_INLINE - void NanSetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { - v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb); - } - - NAN_INLINE bool NanIdleNotification(int idle_time_in_ms) { - return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms); - } - - NAN_INLINE void NanLowMemoryNotification() { - v8::Isolate::GetCurrent()->LowMemoryNotification(); - } - - NAN_INLINE void NanContextDisposedNotification() { - v8::Isolate::GetCurrent()->ContextDisposedNotification(); - } -#else - NAN_INLINE - void NanSetCounterFunction(v8::CounterLookupCallback cb) { - v8::V8::SetCounterFunction(cb); - } - - NAN_INLINE - void NanSetCreateHistogramFunction(v8::CreateHistogramCallback cb) { - v8::V8::SetCreateHistogramFunction(cb); - } - - NAN_INLINE - void NanSetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { - v8::V8::SetAddHistogramSampleFunction(cb); - } - - NAN_INLINE bool NanIdleNotification(int idle_time_in_ms) { - return v8::V8::IdleNotification(idle_time_in_ms); - } - - NAN_INLINE void NanLowMemoryNotification() { - v8::V8::LowMemoryNotification(); - } - - NAN_INLINE void NanContextDisposedNotification() { - v8::V8::ContextDisposedNotification(); - } -#endif - -#if (NODE_MODULE_VERSION > 0x000B) -// Node 0.11+ (0.11.12 and below won't compile with these) - -# define _NAN_METHOD_ARGS_TYPE const v8::FunctionCallbackInfo& -# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args -# define _NAN_METHOD_RETURN_TYPE void - -# define _NAN_GETTER_ARGS_TYPE const v8::PropertyCallbackInfo& -# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args -# define _NAN_GETTER_RETURN_TYPE void - -# define _NAN_SETTER_ARGS_TYPE const v8::PropertyCallbackInfo& -# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args -# define _NAN_SETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_GETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args -# define _NAN_PROPERTY_GETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_SETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args -# define _NAN_PROPERTY_SETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args -# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE void - -# define _NAN_PROPERTY_DELETER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_DELETER_ARGS \ - _NAN_PROPERTY_DELETER_ARGS_TYPE args -# define _NAN_PROPERTY_DELETER_RETURN_TYPE void - -# define _NAN_PROPERTY_QUERY_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args -# define _NAN_PROPERTY_QUERY_RETURN_TYPE void - -# define _NAN_INDEX_GETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args -# define _NAN_INDEX_GETTER_RETURN_TYPE void - -# define _NAN_INDEX_SETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args -# define _NAN_INDEX_SETTER_RETURN_TYPE void - -# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args -# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE void - -# define _NAN_INDEX_DELETER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args -# define _NAN_INDEX_DELETER_RETURN_TYPE void - -# define _NAN_INDEX_QUERY_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args -# define _NAN_INDEX_QUERY_RETURN_TYPE void - -# define NanScope() v8::HandleScope scope(v8::Isolate::GetCurrent()) -# define NanEscapableScope() \ - v8::EscapableHandleScope scope(v8::Isolate::GetCurrent()) - -# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val)) -# define NanLocker() v8::Locker locker(v8::Isolate::GetCurrent()) -# define NanUnlocker() v8::Unlocker unlocker(v8::Isolate::GetCurrent()) -# define NanReturnValue(value) return args.GetReturnValue().Set(value) -# define NanReturnUndefined() return -# define NanReturnHolder() NanReturnValue(args.Holder()) -# define NanReturnThis() NanReturnValue(args.This()) -# define NanReturnNull() return args.GetReturnValue().SetNull() -# define NanReturnEmptyString() return args.GetReturnValue().SetEmptyString() - -# define NanObjectWrapHandle(obj) obj->handle() - - NAN_INLINE v8::Local NanUndefined() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::Undefined(v8::Isolate::GetCurrent()))); - } - - NAN_INLINE v8::Local NanNull() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::Null(v8::Isolate::GetCurrent()))); - } - - NAN_INLINE v8::Local NanTrue() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::True(v8::Isolate::GetCurrent()))); - } - - NAN_INLINE v8::Local NanFalse() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::False(v8::Isolate::GetCurrent()))); - } - - NAN_INLINE int NanAdjustExternalMemory(int bc) { - return static_cast( - v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc)); - } - - NAN_INLINE void NanSetTemplate( - v8::Handle templ - , const char *name - , v8::Handle value) { - templ->Set(v8::Isolate::GetCurrent(), name, value); - } - - NAN_INLINE void NanSetTemplate( - v8::Handle templ - , v8::Handle name - , v8::Handle value - , v8::PropertyAttribute attributes) { - templ->Set(name, value, attributes); - } - - NAN_INLINE v8::Local NanGetCurrentContext() { - return v8::Isolate::GetCurrent()->GetCurrentContext(); - } - - NAN_INLINE void* NanGetInternalFieldPointer( - v8::Handle object - , int index) { - return object->GetAlignedPointerFromInternalField(index); - } - - NAN_INLINE void NanSetInternalFieldPointer( - v8::Handle object - , int index - , void* value) { - object->SetAlignedPointerInInternalField(index, value); - } - -# define NAN_GC_CALLBACK(name) \ - void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags) - - NAN_INLINE void NanAddGCEpilogueCallback( - v8::Isolate::GCEpilogueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter); - } - - NAN_INLINE void NanRemoveGCEpilogueCallback( - v8::Isolate::GCEpilogueCallback callback) { - v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback); - } - - NAN_INLINE void NanAddGCPrologueCallback( - v8::Isolate::GCPrologueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter); - } - - NAN_INLINE void NanRemoveGCPrologueCallback( - v8::Isolate::GCPrologueCallback callback) { - v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback); - } - - NAN_INLINE void NanGetHeapStatistics( - v8::HeapStatistics *heap_statistics) { - v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics); - } - - NAN_DEPRECATED NAN_INLINE v8::Local NanSymbol( - const char* data, int length = -1) { - return NanNew(data, length); - } - - template - NAN_INLINE void NanAssignPersistent( - v8::Persistent& handle - , v8::Handle obj) { - handle.Reset(v8::Isolate::GetCurrent(), obj); - } - - template - NAN_INLINE void NanAssignPersistent( - v8::Persistent& handle - , const v8::Persistent& obj) { - handle.Reset(v8::Isolate::GetCurrent(), obj); - } - - template - class _NanWeakCallbackData; - - template - struct _NanWeakCallbackInfo { - typedef void (*Callback)(const _NanWeakCallbackData& data); - NAN_INLINE _NanWeakCallbackInfo(v8::Handle handle, P* param, Callback cb) - : parameter(param), callback(cb) { - NanAssignPersistent(persistent, handle); - } - - NAN_INLINE ~_NanWeakCallbackInfo() { - persistent.Reset(); - } - - P* const parameter; - Callback const callback; - v8::Persistent persistent; - }; - - template - class _NanWeakCallbackData { - public: - NAN_INLINE _NanWeakCallbackData(_NanWeakCallbackInfo *info) - : info_(info) { } - - NAN_INLINE v8::Local GetValue() const { - return NanNew(info_->persistent); - } - - NAN_INLINE P* GetParameter() const { return info_->parameter; } - - NAN_INLINE bool IsNearDeath() const { - return info_->persistent.IsNearDeath(); - } - - NAN_INLINE void Revive() const; - - NAN_INLINE _NanWeakCallbackInfo* GetCallbackInfo() const { - return info_; - } - - NAN_DEPRECATED NAN_INLINE void Dispose() const { - } - - private: - _NanWeakCallbackInfo* info_; - }; - - template - static void _NanWeakCallbackDispatcher( - const v8::WeakCallbackData > &data) { - _NanWeakCallbackInfo *info = data.GetParameter(); - _NanWeakCallbackData wcbd(info); - info->callback(wcbd); - if (wcbd.IsNearDeath()) { - delete wcbd.GetCallbackInfo(); - } - } - - template - NAN_INLINE void _NanWeakCallbackData::Revive() const { - info_->persistent.SetWeak(info_, &_NanWeakCallbackDispatcher); - } - -template -NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( - v8::Handle handle - , P* parameter - , typename _NanWeakCallbackInfo::Callback callback) { - _NanWeakCallbackInfo *cbinfo = - new _NanWeakCallbackInfo(handle, parameter, callback); - cbinfo->persistent.SetWeak(cbinfo, &_NanWeakCallbackDispatcher); - return cbinfo; -} - -# define NAN_WEAK_CALLBACK(name) \ - template \ - static void name(const _NanWeakCallbackData &data) - -# define _NAN_ERROR(fun, errmsg) fun(NanNew(errmsg)) - -# define _NAN_THROW_ERROR(fun, errmsg) \ - do { \ - NanScope(); \ - v8::Isolate::GetCurrent()->ThrowException(_NAN_ERROR(fun, errmsg)); \ - } while (0); - - NAN_INLINE v8::Local NanError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::Error, errmsg); - } - - NAN_INLINE void NanThrowError(const char* errmsg) { - _NAN_THROW_ERROR(v8::Exception::Error, errmsg); - } - - NAN_INLINE void NanThrowError(v8::Handle error) { - NanScope(); - v8::Isolate::GetCurrent()->ThrowException(error); - } - - NAN_INLINE v8::Local NanError( - const char *msg - , const int errorNumber - ) { - v8::Local err = v8::Exception::Error(NanNew(msg)); - v8::Local obj = err.As(); - obj->Set(NanNew("code"), NanNew(errorNumber)); - return err; - } - - NAN_INLINE void NanThrowError( - const char *msg - , const int errorNumber - ) { - NanThrowError(NanError(msg, errorNumber)); - } - - NAN_INLINE v8::Local NanTypeError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::TypeError, errmsg); - } - - NAN_INLINE void NanThrowTypeError(const char* errmsg) { - _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); - } - - NAN_INLINE v8::Local NanRangeError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::RangeError, errmsg); - } - - NAN_INLINE void NanThrowRangeError(const char* errmsg) { - _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); - } - - template NAN_INLINE void NanDisposePersistent( - v8::Persistent &handle - ) { - handle.Reset(); - } - - NAN_INLINE v8::Local NanNewBufferHandle ( - char *data - , size_t length - , node::smalloc::FreeCallback callback - , void *hint - ) { - return node::Buffer::New( - v8::Isolate::GetCurrent(), data, length, callback, hint); - } - - NAN_INLINE v8::Local NanNewBufferHandle ( - const char *data - , uint32_t size - ) { - return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); - } - - NAN_INLINE v8::Local NanNewBufferHandle (uint32_t size) { - return node::Buffer::New(v8::Isolate::GetCurrent(), size); - } - - NAN_INLINE v8::Local NanBufferUse( - char* data - , uint32_t size - ) { - return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size); - } - - NAN_INLINE bool NanHasInstance( - const v8::Persistent& function_template - , v8::Handle value - ) { - return NanNew(function_template)->HasInstance(value); - } - - NAN_DEPRECATED NAN_INLINE v8::Local NanNewContextHandle( - v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle() - ) { - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - return v8::Local::New( - isolate - , v8::Context::New(isolate, extensions, tmpl, obj) - ); - } - - NAN_INLINE v8::Local NanCompileScript( - v8::Local s - , const v8::ScriptOrigin& origin - ) { - v8::ScriptCompiler::Source source(s, origin); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); - } - - NAN_INLINE v8::Local NanCompileScript( - v8::Local s - ) { - v8::ScriptCompiler::Source source(s); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); - } - - NAN_INLINE v8::Local NanRunScript( - v8::Handle script - ) { - return script->BindToCurrentContext()->Run(); - } - - NAN_INLINE v8::Local NanRunScript( - v8::Handle script - ) { - return script->Run(); - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , v8::Handle func - , int argc - , v8::Handle* argv) { - return NanNew(node::MakeCallback( - v8::Isolate::GetCurrent(), target, func, argc, argv)); - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , v8::Handle symbol - , int argc - , v8::Handle* argv) { - return NanNew(node::MakeCallback( - v8::Isolate::GetCurrent(), target, symbol, argc, argv)); - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , const char* method - , int argc - , v8::Handle* argv) { - return NanNew(node::MakeCallback( - v8::Isolate::GetCurrent(), target, method, argc, argv)); - } - - template - NAN_INLINE void NanSetIsolateData( - v8::Isolate *isolate - , T *data - ) { - isolate->SetData(0, data); - } - - template - NAN_INLINE T *NanGetIsolateData( - v8::Isolate *isolate - ) { - return static_cast(isolate->GetData(0)); - } - - class NanAsciiString { - public: - NAN_INLINE explicit NanAsciiString(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Length(); - buf = new char[size + 1]; - size = toStr->WriteOneByte(reinterpret_cast(buf)); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - - NAN_INLINE char* operator*() { return buf; } - NAN_INLINE const char* operator*() const { return buf; } - - NAN_INLINE ~NanAsciiString() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanAsciiString(const NanAsciiString&); - void operator=(const NanAsciiString&); - - char *buf; - int size; - }; - - class NanUtf8String { - public: - NAN_INLINE explicit NanUtf8String(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Utf8Length(); - buf = new char[size + 1]; - toStr->WriteUtf8(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - NAN_INLINE char* operator*() { return buf; } - NAN_INLINE const char* operator*() const { return buf; } - - NAN_INLINE ~NanUtf8String() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanUtf8String(const NanUtf8String&); - void operator=(const NanUtf8String&); - - char *buf; - int size; - }; - - class NanUcs2String { - public: - NAN_INLINE explicit NanUcs2String(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Length(); - buf = new uint16_t[size + 1]; - toStr->Write(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - NAN_INLINE uint16_t* operator*() { return buf; } - NAN_INLINE const uint16_t* operator*() const { return buf; } - - NAN_INLINE ~NanUcs2String() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanUcs2String(const NanUcs2String&); - void operator=(const NanUcs2String&); - - uint16_t *buf; - int size; - }; - -#else -// Node 0.8 and 0.10 - -# define _NAN_METHOD_ARGS_TYPE const v8::Arguments& -# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args -# define _NAN_METHOD_RETURN_TYPE v8::Handle - -# define _NAN_GETTER_ARGS_TYPE const v8::AccessorInfo & -# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args -# define _NAN_GETTER_RETURN_TYPE v8::Handle - -# define _NAN_SETTER_ARGS_TYPE const v8::AccessorInfo & -# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args -# define _NAN_SETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_GETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args -# define _NAN_PROPERTY_GETTER_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_SETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args -# define _NAN_PROPERTY_SETTER_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args -# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_DELETER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_DELETER_ARGS _NAN_PROPERTY_DELETER_ARGS_TYPE args -# define _NAN_PROPERTY_DELETER_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_QUERY_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args -# define _NAN_PROPERTY_QUERY_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_GETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args -# define _NAN_INDEX_GETTER_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_SETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args -# define _NAN_INDEX_SETTER_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args -# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_DELETER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args -# define _NAN_INDEX_DELETER_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_QUERY_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args -# define _NAN_INDEX_QUERY_RETURN_TYPE v8::Handle - - NAN_DEPRECATED NAN_INLINE v8::Local NanSymbol( - const char* data, int length = -1) { - return v8::String::NewSymbol(data, length); - } - -# define NanScope() v8::HandleScope scope -# define NanEscapableScope() v8::HandleScope scope -# define NanEscapeScope(val) scope.Close(val) -# define NanLocker() v8::Locker locker -# define NanUnlocker() v8::Unlocker unlocker -# define NanReturnValue(value) return scope.Close(value) -# define NanReturnHolder() NanReturnValue(args.Holder()) -# define NanReturnThis() NanReturnValue(args.This()) -# define NanReturnUndefined() return v8::Undefined() -# define NanReturnNull() return v8::Null() -# define NanReturnEmptyString() return v8::String::Empty() -# define NanObjectWrapHandle(obj) v8::Local::New(obj->handle_) - - NAN_INLINE v8::Local NanUndefined() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::Undefined())); - } - - NAN_INLINE v8::Local NanNull() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::Null())); - } - - NAN_INLINE v8::Local NanTrue() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::True())); - } - - NAN_INLINE v8::Local NanFalse() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::False())); - } - - NAN_INLINE int NanAdjustExternalMemory(int bc) { - return static_cast(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc)); - } - - NAN_INLINE void NanSetTemplate( - v8::Handle templ - , const char *name - , v8::Handle value) { - templ->Set(name, value); - } - - NAN_INLINE void NanSetTemplate( - v8::Handle templ - , v8::Handle name - , v8::Handle value - , v8::PropertyAttribute attributes) { - templ->Set(name, value, attributes); - } - - NAN_INLINE v8::Local NanGetCurrentContext() { - return v8::Context::GetCurrent(); - } - - NAN_INLINE void* NanGetInternalFieldPointer( - v8::Handle object - , int index) { - return object->GetPointerFromInternalField(index); - } - - NAN_INLINE void NanSetInternalFieldPointer( - v8::Handle object - , int index - , void* value) { - object->SetPointerInInternalField(index, value); - } - -# define NAN_GC_CALLBACK(name) \ - void name(v8::GCType type, v8::GCCallbackFlags flags) - - NAN_INLINE void NanAddGCEpilogueCallback( - v8::GCEpilogueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::V8::AddGCEpilogueCallback(callback, gc_type_filter); - } - NAN_INLINE void NanRemoveGCEpilogueCallback( - v8::GCEpilogueCallback callback) { - v8::V8::RemoveGCEpilogueCallback(callback); - } - NAN_INLINE void NanAddGCPrologueCallback( - v8::GCPrologueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::V8::AddGCPrologueCallback(callback, gc_type_filter); - } - NAN_INLINE void NanRemoveGCPrologueCallback( - v8::GCPrologueCallback callback) { - v8::V8::RemoveGCPrologueCallback(callback); - } - NAN_INLINE void NanGetHeapStatistics( - v8::HeapStatistics *heap_statistics) { - v8::V8::GetHeapStatistics(heap_statistics); - } - - template - NAN_INLINE void NanAssignPersistent( - v8::Persistent& handle - , v8::Handle obj) { - handle.Dispose(); - handle = v8::Persistent::New(obj); - } - - template - class _NanWeakCallbackData; - - template - struct _NanWeakCallbackInfo { - typedef void (*Callback)(const _NanWeakCallbackData &data); - NAN_INLINE _NanWeakCallbackInfo(v8::Handle handle, P* param, Callback cb) - : parameter(param) - , callback(cb) - , persistent(v8::Persistent::New(handle)) { } - - NAN_INLINE ~_NanWeakCallbackInfo() { - persistent.Dispose(); - persistent.Clear(); - } - - P* const parameter; - Callback const callback; - v8::Persistent persistent; - }; - - template - class _NanWeakCallbackData { - public: - NAN_INLINE _NanWeakCallbackData(_NanWeakCallbackInfo *info) - : info_(info) { } - - NAN_INLINE v8::Local GetValue() const { - return NanNew(info_->persistent); - } - - NAN_INLINE P* GetParameter() const { return info_->parameter; } - - NAN_INLINE bool IsNearDeath() const { - return info_->persistent.IsNearDeath(); - } - - NAN_INLINE void Revive() const; - - NAN_INLINE _NanWeakCallbackInfo* GetCallbackInfo() const { - return info_; - } - - NAN_DEPRECATED NAN_INLINE void Dispose() const { - } - - private: - _NanWeakCallbackInfo* info_; - }; - - template - static void _NanWeakPersistentDispatcher( - v8::Persistent object, void *data) { - _NanWeakCallbackInfo* info = - static_cast<_NanWeakCallbackInfo*>(data); - _NanWeakCallbackData wcbd(info); - info->callback(wcbd); - if (wcbd.IsNearDeath()) { - delete wcbd.GetCallbackInfo(); - } - } - - template - NAN_INLINE void _NanWeakCallbackData::Revive() const { - info_->persistent.MakeWeak( - info_ - , &_NanWeakPersistentDispatcher); - } - - template - NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( - v8::Handle handle - , P* parameter - , typename _NanWeakCallbackInfo::Callback callback) { - _NanWeakCallbackInfo *cbinfo = - new _NanWeakCallbackInfo(handle, parameter, callback); - cbinfo->persistent.MakeWeak( - cbinfo - , &_NanWeakPersistentDispatcher); - return cbinfo; - } - -# define NAN_WEAK_CALLBACK(name) \ - template \ - static void name(const _NanWeakCallbackData &data) - -# define _NAN_ERROR(fun, errmsg) \ - fun(v8::String::New(errmsg)) - -# define _NAN_THROW_ERROR(fun, errmsg) \ - do { \ - NanScope(); \ - return v8::Local::New( \ - v8::ThrowException(_NAN_ERROR(fun, errmsg))); \ - } while (0); - - NAN_INLINE v8::Local NanError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::Error, errmsg); - } - - NAN_INLINE v8::Local NanThrowError(const char* errmsg) { - _NAN_THROW_ERROR(v8::Exception::Error, errmsg); - } - - NAN_INLINE v8::Local NanThrowError( - v8::Handle error - ) { - NanScope(); - return v8::Local::New(v8::ThrowException(error)); - } - - NAN_INLINE v8::Local NanError( - const char *msg - , const int errorNumber - ) { - v8::Local err = v8::Exception::Error(v8::String::New(msg)); - v8::Local obj = err.As(); - obj->Set(v8::String::New("code"), v8::Int32::New(errorNumber)); - return err; - } - - NAN_INLINE v8::Local NanThrowError( - const char *msg - , const int errorNumber - ) { - return NanThrowError(NanError(msg, errorNumber)); - } - - NAN_INLINE v8::Local NanTypeError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::TypeError, errmsg); - } - - NAN_INLINE v8::Local NanThrowTypeError( - const char* errmsg - ) { - _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); - } - - NAN_INLINE v8::Local NanRangeError( - const char* errmsg - ) { - return _NAN_ERROR(v8::Exception::RangeError, errmsg); - } - - NAN_INLINE v8::Local NanThrowRangeError( - const char* errmsg - ) { - _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); - } - - template - NAN_INLINE void NanDisposePersistent( - v8::Persistent &handle) { // NOLINT(runtime/references) - handle.Dispose(); - handle.Clear(); - } - - NAN_INLINE v8::Local NanNewBufferHandle ( - char *data - , size_t length - , node::Buffer::free_callback callback - , void *hint - ) { - return NanNew( - node::Buffer::New(data, length, callback, hint)->handle_); - } - - NAN_INLINE v8::Local NanNewBufferHandle ( - const char *data - , uint32_t size - ) { -#if NODE_MODULE_VERSION >= 0x000B - return NanNew(node::Buffer::New(data, size)->handle_); -#else - return NanNew( - node::Buffer::New(const_cast(data), size)->handle_); -#endif - } - - NAN_INLINE v8::Local NanNewBufferHandle (uint32_t size) { - return NanNew(node::Buffer::New(size)->handle_); - } - - NAN_INLINE void FreeData(char *data, void *hint) { - delete[] data; - } - - NAN_INLINE v8::Local NanBufferUse( - char* data - , uint32_t size - ) { - return NanNew( - node::Buffer::New(data, size, FreeData, NULL)->handle_); - } - - NAN_INLINE bool NanHasInstance( - const v8::Persistent& function_template - , v8::Handle value - ) { - return function_template->HasInstance(value); - } - - NAN_DEPRECATED NAN_INLINE v8::Local NanNewContextHandle( - v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle() - ) { - v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); - v8::Local lctx = NanNew(ctx); - ctx.Dispose(); - return lctx; - } - - NAN_INLINE v8::Local NanCompileScript( - v8::Local s - , const v8::ScriptOrigin& origin - ) { - return v8::Script::Compile(s, const_cast(&origin)); - } - - NAN_INLINE v8::Local NanCompileScript( - v8::Local s - ) { - return v8::Script::Compile(s); - } - - NAN_INLINE v8::Local NanRunScript(v8::Handle script) { - return script->Run(); - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , v8::Handle func - , int argc - , v8::Handle* argv) { -# if NODE_VERSION_AT_LEAST(0, 8, 0) - return NanNew(node::MakeCallback(target, func, argc, argv)); -# else - v8::TryCatch try_catch; - v8::Local result = func->Call(target, argc, argv); - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - return result; -# endif - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , v8::Handle symbol - , int argc - , v8::Handle* argv) { -# if NODE_VERSION_AT_LEAST(0, 8, 0) - return NanNew(node::MakeCallback(target, symbol, argc, argv)); -# else - v8::Local callback = target->Get(symbol).As(); - return NanMakeCallback(target, callback, argc, argv); -# endif - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , const char* method - , int argc - , v8::Handle* argv) { -# if NODE_VERSION_AT_LEAST(0, 8, 0) - return NanNew(node::MakeCallback(target, method, argc, argv)); -# else - return NanMakeCallback(target, NanNew(method), argc, argv); -# endif - } - - template - NAN_INLINE void NanSetIsolateData( - v8::Isolate *isolate - , T *data - ) { - isolate->SetData(data); - } - - template - NAN_INLINE T *NanGetIsolateData( - v8::Isolate *isolate - ) { - return static_cast(isolate->GetData()); - } - - class NanAsciiString { - public: - NAN_INLINE explicit NanAsciiString(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Length(); - buf = new char[size + 1]; - size = toStr->WriteAscii(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - - NAN_INLINE char* operator*() { return buf; } - NAN_INLINE const char* operator*() const { return buf; } - - NAN_INLINE ~NanAsciiString() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanAsciiString(const NanAsciiString&); - void operator=(const NanAsciiString&); - - char *buf; - int size; - }; - - class NanUtf8String { - public: - NAN_INLINE explicit NanUtf8String(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Utf8Length(); - buf = new char[size + 1]; - toStr->WriteUtf8(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - NAN_INLINE char* operator*() { return buf; } - NAN_INLINE const char* operator*() const { return buf; } - - NAN_INLINE ~NanUtf8String() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanUtf8String(const NanUtf8String&); - void operator=(const NanUtf8String&); - - char *buf; - int size; - }; - - class NanUcs2String { - public: - NAN_INLINE explicit NanUcs2String(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Length(); - buf = new uint16_t[size + 1]; - toStr->Write(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - NAN_INLINE uint16_t* operator*() { return buf; } - NAN_INLINE const uint16_t* operator*() const { return buf; } - - NAN_INLINE ~NanUcs2String() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanUcs2String(const NanUcs2String&); - void operator=(const NanUcs2String&); - - uint16_t *buf; - int size; - }; - -#endif // NODE_MODULE_VERSION - -typedef void (*NanFreeCallback)(char *data, void *hint); - -#define NAN_METHOD(name) _NAN_METHOD_RETURN_TYPE name(_NAN_METHOD_ARGS) -#define NAN_GETTER(name) \ - _NAN_GETTER_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_GETTER_ARGS) -#define NAN_SETTER(name) \ - _NAN_SETTER_RETURN_TYPE name( \ - v8::Local property \ - , v8::Local value \ - , _NAN_SETTER_ARGS) -#define NAN_PROPERTY_GETTER(name) \ - _NAN_PROPERTY_GETTER_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_PROPERTY_GETTER_ARGS) -#define NAN_PROPERTY_SETTER(name) \ - _NAN_PROPERTY_SETTER_RETURN_TYPE name( \ - v8::Local property \ - , v8::Local value \ - , _NAN_PROPERTY_SETTER_ARGS) -#define NAN_PROPERTY_ENUMERATOR(name) \ - _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name(_NAN_PROPERTY_ENUMERATOR_ARGS) -#define NAN_PROPERTY_DELETER(name) \ - _NAN_PROPERTY_DELETER_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_PROPERTY_DELETER_ARGS) -#define NAN_PROPERTY_QUERY(name) \ - _NAN_PROPERTY_QUERY_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_PROPERTY_QUERY_ARGS) -# define NAN_INDEX_GETTER(name) \ - _NAN_INDEX_GETTER_RETURN_TYPE name(uint32_t index, _NAN_INDEX_GETTER_ARGS) -#define NAN_INDEX_SETTER(name) \ - _NAN_INDEX_SETTER_RETURN_TYPE name( \ - uint32_t index \ - , v8::Local value \ - , _NAN_INDEX_SETTER_ARGS) -#define NAN_INDEX_ENUMERATOR(name) \ - _NAN_INDEX_ENUMERATOR_RETURN_TYPE name(_NAN_INDEX_ENUMERATOR_ARGS) -#define NAN_INDEX_DELETER(name) \ - _NAN_INDEX_DELETER_RETURN_TYPE name( \ - uint32_t index \ - , _NAN_INDEX_DELETER_ARGS) -#define NAN_INDEX_QUERY(name) \ - _NAN_INDEX_QUERY_RETURN_TYPE name(uint32_t index, _NAN_INDEX_QUERY_ARGS) - -class NanCallback { - public: - NanCallback() { - NanScope(); - v8::Local obj = NanNew(); - NanAssignPersistent(handle, obj); - } - - explicit NanCallback(const v8::Handle &fn) { - NanScope(); - v8::Local obj = NanNew(); - NanAssignPersistent(handle, obj); - SetFunction(fn); - } - - ~NanCallback() { - if (handle.IsEmpty()) return; - NanDisposePersistent(handle); - } - - NAN_INLINE void SetFunction(const v8::Handle &fn) { - NanScope(); - NanNew(handle)->Set(kCallbackIndex, fn); - } - - NAN_INLINE v8::Local GetFunction() const { - NanEscapableScope(); - return NanEscapeScope(NanNew(handle)->Get(kCallbackIndex) - .As()); - } - - NAN_INLINE bool IsEmpty() const { - NanScope(); - return NanNew(handle)->Get(kCallbackIndex)->IsUndefined(); - } - - v8::Handle Call(int argc, v8::Handle argv[]) const { - NanEscapableScope(); -#if (NODE_MODULE_VERSION > 0x000B) // 0.11.12+ - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - v8::Local callback = NanNew(handle)-> - Get(kCallbackIndex).As(); - return NanEscapeScope(node::MakeCallback( - isolate - , isolate->GetCurrentContext()->Global() - , callback - , argc - , argv - )); -#else -#if NODE_VERSION_AT_LEAST(0, 8, 0) - v8::Local callback = handle-> - Get(kCallbackIndex).As(); - return NanEscapeScope(node::MakeCallback( - v8::Context::GetCurrent()->Global() - , callback - , argc - , argv - )); -#else - v8::Local callback = handle-> - Get(kCallbackIndex).As(); - return NanEscapeScope(NanMakeCallback( - v8::Context::GetCurrent()->Global(), callback, argc, argv)); -#endif -#endif - } - - private: - v8::Persistent handle; - static const uint32_t kCallbackIndex = 0; -}; - -/* abstract */ class NanAsyncWorker { - public: - explicit NanAsyncWorker(NanCallback *callback_) - : callback(callback_), errmsg_(NULL) { - request.data = this; - - NanScope(); - v8::Local obj = NanNew(); - NanAssignPersistent(persistentHandle, obj); - } - - virtual ~NanAsyncWorker() { - NanScope(); - - if (!persistentHandle.IsEmpty()) - NanDisposePersistent(persistentHandle); - if (callback) - delete callback; - if (errmsg_) - delete[] errmsg_; - } - - virtual void WorkComplete() { - NanScope(); - - if (errmsg_ == NULL) - HandleOKCallback(); - else - HandleErrorCallback(); - delete callback; - callback = NULL; - } - - NAN_INLINE void SaveToPersistent( - const char *key, const v8::Local &obj) { - v8::Local handle = NanNew(persistentHandle); - handle->Set(NanNew(key), obj); - } - - v8::Local GetFromPersistent(const char *key) const { - NanEscapableScope(); - v8::Local handle = NanNew(persistentHandle); - return NanEscapeScope(handle->Get(NanNew(key)).As()); - } - - virtual void Execute() = 0; - - uv_work_t request; - - virtual void Destroy() { - delete this; - } - - protected: - v8::Persistent persistentHandle; - NanCallback *callback; - - virtual void HandleOKCallback() { - callback->Call(0, NULL); - } - - virtual void HandleErrorCallback() { - NanScope(); - - v8::Local argv[] = { - v8::Exception::Error(NanNew(ErrorMessage())) - }; - callback->Call(1, argv); - } - - void SetErrorMessage(const char *msg) { - if (errmsg_) { - delete[] errmsg_; - } - - size_t size = strlen(msg) + 1; - errmsg_ = new char[size]; - memcpy(errmsg_, msg, size); - } - - const char* ErrorMessage() const { - return errmsg_; - } - - private: - char *errmsg_; -}; - -/* abstract */ class NanAsyncProgressWorker : public NanAsyncWorker { - public: - explicit NanAsyncProgressWorker(NanCallback *callback_) - : NanAsyncWorker(callback_), asyncdata_(NULL), asyncsize_(0) { - async = new uv_async_t; - uv_async_init( - uv_default_loop() - , async - , AsyncProgress_ - ); - async->data = this; - - uv_mutex_init(&async_lock); - } - - virtual ~NanAsyncProgressWorker() { - uv_mutex_destroy(&async_lock); - - if (asyncdata_) { - delete[] asyncdata_; - } - } - - void WorkProgress() { - uv_mutex_lock(&async_lock); - char *data = asyncdata_; - size_t size = asyncsize_; - asyncdata_ = NULL; - uv_mutex_unlock(&async_lock); - - // Dont send progress events after we've already completed. - if (callback) { - HandleProgressCallback(data, size); - } - delete[] data; - } - - class ExecutionProgress { - friend class NanAsyncProgressWorker; - public: - // You could do fancy generics with templates here. - void Send(const char* data, size_t size) const { - that_->SendProgress_(data, size); - } - - private: - explicit ExecutionProgress(NanAsyncProgressWorker* that) : that_(that) {} - // Prohibit copying and assignment. - ExecutionProgress(const ExecutionProgress&); - void operator=(const ExecutionProgress&); - #if __cplusplus >= 201103L - // Prohibit C++11 move semantics. - ExecutionProgress(ExecutionProgress&&) = delete; - void operator=(ExecutionProgress&&) = delete; - #endif - NanAsyncProgressWorker* const that_; - }; - - virtual void Execute(const ExecutionProgress& progress) = 0; - virtual void HandleProgressCallback(const char *data, size_t size) = 0; - - virtual void Destroy() { - uv_close(reinterpret_cast(async), AsyncClose_); - } - - private: - void Execute() /*final override*/ { - ExecutionProgress progress(this); - Execute(progress); - } - - void SendProgress_(const char *data, size_t size) { - char *new_data = new char[size]; - memcpy(new_data, data, size); - - uv_mutex_lock(&async_lock); - char *old_data = asyncdata_; - asyncdata_ = new_data; - asyncsize_ = size; - uv_mutex_unlock(&async_lock); - - if (old_data) { - delete[] old_data; - } - uv_async_send(async); - } - - NAN_INLINE static NAUV_WORK_CB(AsyncProgress_) { - NanAsyncProgressWorker *worker = - static_cast(async->data); - worker->WorkProgress(); - } - - NAN_INLINE static void AsyncClose_(uv_handle_t* handle) { - NanAsyncProgressWorker *worker = - static_cast(handle->data); - delete reinterpret_cast(handle); - delete worker; - } - - uv_async_t *async; - uv_mutex_t async_lock; - char *asyncdata_; - size_t asyncsize_; -}; - -NAN_INLINE void NanAsyncExecute (uv_work_t* req) { - NanAsyncWorker *worker = static_cast(req->data); - worker->Execute(); -} - -NAN_INLINE void NanAsyncExecuteComplete (uv_work_t* req) { - NanAsyncWorker* worker = static_cast(req->data); - worker->WorkComplete(); - worker->Destroy(); -} - -NAN_INLINE void NanAsyncQueueWorker (NanAsyncWorker* worker) { - uv_queue_work( - uv_default_loop() - , &worker->request - , NanAsyncExecute - , (uv_after_work_cb)NanAsyncExecuteComplete - ); -} - -//// Base 64 //// - -#define _nan_base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) - -// Doesn't check for padding at the end. Can be 1-2 bytes over. -NAN_INLINE size_t _nan_base64_decoded_size_fast(size_t size) { - size_t remainder = size % 4; - - size = (size / 4) * 3; - if (remainder) { - if (size == 0 && remainder == 1) { - // special case: 1-byte input cannot be decoded - size = 0; - } else { - // non-padded input, add 1 or 2 extra bytes - size += 1 + (remainder == 3); - } - } - - return size; -} - -template -NAN_INLINE size_t _nan_base64_decoded_size( - const T* src - , size_t size -) { - if (size == 0) - return 0; - - if (src[size - 1] == '=') - size--; - if (size > 0 && src[size - 1] == '=') - size--; - - return _nan_base64_decoded_size_fast(size); -} - -// supports regular and URL-safe base64 -static const int _nan_unbase64_table[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63 - , 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1 - , -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 - , 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63 - , -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 - , 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 -}; - -#define _nan_unbase64(x) _nan_unbase64_table[(uint8_t)(x)] - -template static size_t _nan_base64_decode( - char* buf - , size_t len - , const T* src - , const size_t srcLen -) { - char* dst = buf; - char* dstEnd = buf + len; - const T* srcEnd = src + srcLen; - - while (src < srcEnd && dst < dstEnd) { - ptrdiff_t remaining = srcEnd - src; - char a, b, c, d; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining == 0 || *src == '=') break; - a = _nan_unbase64(*src++); - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 1 || *src == '=') break; - b = _nan_unbase64(*src++); - - *dst++ = (a << 2) | ((b & 0x30) >> 4); - if (dst == dstEnd) break; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 2 || *src == '=') break; - c = _nan_unbase64(*src++); - - *dst++ = ((b & 0x0F) << 4) | ((c & 0x3C) >> 2); - if (dst == dstEnd) break; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 3 || *src == '=') break; - d = _nan_unbase64(*src++); - - *dst++ = ((c & 0x03) << 6) | (d & 0x3F); - } - - return dst - buf; -} - -//// HEX //// - -template unsigned _nan_hex2bin(T c) { - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); - if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); - return static_cast(-1); -} - -template static size_t _nan_hex_decode( - char* buf - , size_t len - , const T* src - , const size_t srcLen -) { - size_t i; - for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) { - unsigned a = _nan_hex2bin(src[i * 2 + 0]); - unsigned b = _nan_hex2bin(src[i * 2 + 1]); - if (!~a || !~b) return i; - buf[i] = a * 16 + b; - } - - return i; -} - -namespace NanIntern { - -inline -NanExternalOneByteStringResource const* -GetExternalResource(v8::Local str) { -#if NODE_MODULE_VERSION < 42 - return str->GetExternalAsciiStringResource(); -#else // io.js v1.0.0 - return str->GetExternalOneByteStringResource(); -#endif -} - -inline -bool -IsExternal(v8::Local str) { -#if NODE_MODULE_VERSION < 42 - return str->IsExternalAscii(); -#else // io.js v1.0.0 - return str->IsExternalOneByte(); -#endif -} - -} // end of namespace NanIntern - -static bool _NanGetExternalParts( - v8::Handle val - , const char** data - , size_t* len -) { - if (node::Buffer::HasInstance(val)) { - *data = node::Buffer::Data(val.As()); - *len = node::Buffer::Length(val.As()); - return true; - } - - assert(val->IsString()); - v8::Local str = NanNew(val.As()); - - if (NanIntern::IsExternal(str)) { - const NanExternalOneByteStringResource* ext; - ext = NanIntern::GetExternalResource(str); - *data = ext->data(); - *len = ext->length(); - return true; - } - - if (str->IsExternal()) { - const v8::String::ExternalStringResource* ext; - ext = str->GetExternalStringResource(); - *data = reinterpret_cast(ext->data()); - *len = ext->length(); - return true; - } - - return false; -} - -namespace Nan { - enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; -} - -#if !NODE_VERSION_AT_LEAST(0, 10, 0) -# include "nan_string_bytes.h" // NOLINT(build/include) -#endif - -NAN_INLINE v8::Local NanEncode( - const void *buf, size_t len, enum Nan::Encoding encoding = Nan::BINARY) { -#if (NODE_MODULE_VERSION >= 42) - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - node::encoding node_enc = static_cast(encoding); - - if (encoding == Nan::UCS2) { - return node::Encode( - isolate - , reinterpret_cast(buf) - , len / 2); - } else { - return node::Encode( - isolate - , reinterpret_cast(buf) - , len - , node_enc); - } -#elif (NODE_MODULE_VERSION > 0x000B) - return node::Encode( - v8::Isolate::GetCurrent() - , buf, len - , static_cast(encoding)); -#else -# if NODE_VERSION_AT_LEAST(0, 10, 0) - return node::Encode(buf, len, static_cast(encoding)); -# else - return NanIntern::Encode(reinterpret_cast(buf), len, encoding); -# endif -#endif -} - -NAN_INLINE ssize_t NanDecodeBytes( - v8::Handle val, enum Nan::Encoding encoding = Nan::BINARY) { -#if (NODE_MODULE_VERSION > 0x000B) - return node::DecodeBytes( - v8::Isolate::GetCurrent() - , val - , static_cast(encoding)); -#else -# if (NODE_MODULE_VERSION < 0x000B) - if (encoding == Nan::BUFFER) { - return node::DecodeBytes(val, node::BINARY); - } -# endif - return node::DecodeBytes(val, static_cast(encoding)); -#endif -} - -NAN_INLINE ssize_t NanDecodeWrite( - char *buf - , size_t len - , v8::Handle val - , enum Nan::Encoding encoding = Nan::BINARY) { -#if (NODE_MODULE_VERSION > 0x000B) - return node::DecodeWrite( - v8::Isolate::GetCurrent() - , buf - , len - , val - , static_cast(encoding)); -#else -# if (NODE_MODULE_VERSION < 0x000B) - if (encoding == Nan::BUFFER) { - return node::DecodeWrite(buf, len, val, node::BINARY); - } -# endif - return node::DecodeWrite( - buf - , len - , val - , static_cast(encoding)); -#endif -} - -/* NAN_DEPRECATED */ NAN_INLINE void* _NanRawString( - v8::Handle from - , enum Nan::Encoding encoding - , size_t *datalen - , void *buf - , size_t buflen - , int flags -) { - NanScope(); - - size_t sz_; - size_t term_len = !(flags & v8::String::NO_NULL_TERMINATION); - char *data = NULL; - size_t len; - bool is_extern = _NanGetExternalParts( - from - , const_cast(&data) - , &len); - - if (is_extern && !term_len) { - NanSetPointerSafe(datalen, len); - return data; - } - - v8::Local toStr = from->ToString(); - - char *to = static_cast(buf); - - switch (encoding) { - case Nan::ASCII: -#if NODE_MODULE_VERSION < 0x000C - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , toStr->WriteAscii(to, 0, static_cast(sz_ + term_len), flags)); - return to; -#endif - case Nan::BINARY: - case Nan::BUFFER: - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } -#if NODE_MODULE_VERSION < 0x000C - { - uint16_t* twobytebuf = new uint16_t[sz_ + term_len]; - - size_t somelen = toStr->Write(twobytebuf, 0, - static_cast(sz_ + term_len), flags); - - for (size_t i = 0; i < sz_ + term_len && i < somelen + term_len; i++) { - unsigned char *b = reinterpret_cast(&twobytebuf[i]); - to[i] = *b; - } - - NanSetPointerSafe(datalen, somelen); - - delete[] twobytebuf; - return to; - } -#else - NanSetPointerSafe( - datalen, - toStr->WriteOneByte( - reinterpret_cast(to) - , 0 - , static_cast(sz_ + term_len) - , flags)); - return to; -#endif - case Nan::UTF8: - sz_ = toStr->Utf8Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , toStr->WriteUtf8(to, static_cast(sz_ + term_len) - , NULL, flags) - - term_len); - return to; - case Nan::BASE64: - { - v8::String::Value value(toStr); - sz_ = _nan_base64_decoded_size(*value, value.length()); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len); - } - NanSetPointerSafe( - datalen - , _nan_base64_decode(to, sz_, *value, value.length())); - if (term_len) { - to[sz_] = '\0'; - } - return to; - } - case Nan::UCS2: - { - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[(sz_ + term_len) * 2]; - } else { - assert(buflen >= (sz_ + term_len) * 2 && "too small buffer"); - } - - int bc = 2 * toStr->Write( - reinterpret_cast(to) - , 0 - , static_cast(sz_ + term_len) - , flags); - NanSetPointerSafe(datalen, bc); - return to; - } - case Nan::HEX: - { - v8::String::Value value(toStr); - sz_ = value.length(); - assert(!(sz_ & 1) && "bad hex data"); - if (to == NULL) { - to = new char[sz_ / 2 + term_len]; - } else { - assert(buflen >= sz_ / 2 + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , _nan_hex_decode(to, sz_ / 2, *value, value.length())); - } - if (term_len) { - to[sz_ / 2] = '\0'; - } - return to; - default: - assert(0 && "unknown encoding"); - } - return to; -} - -NAN_DEPRECATED NAN_INLINE void* NanRawString( - v8::Handle from - , enum Nan::Encoding encoding - , size_t *datalen - , void *buf - , size_t buflen - , int flags -) { - return _NanRawString(from, encoding, datalen, buf, buflen, flags); -} - - -NAN_DEPRECATED NAN_INLINE char* NanCString( - v8::Handle from - , size_t *datalen - , char *buf = NULL - , size_t buflen = 0 - , int flags = v8::String::NO_OPTIONS -) { - return static_cast( - _NanRawString(from, Nan::UTF8, datalen, buf, buflen, flags) - ); -} - -NAN_INLINE void NanSetPrototypeTemplate( - v8::Local templ - , const char *name - , v8::Handle value -) { - NanSetTemplate(templ->PrototypeTemplate(), name, value); -} - -NAN_INLINE void NanSetPrototypeTemplate( - v8::Local templ - , v8::Handle name - , v8::Handle value - , v8::PropertyAttribute attributes -) { - NanSetTemplate(templ->PrototypeTemplate(), name, value, attributes); -} - -NAN_INLINE void NanSetInstanceTemplate( - v8::Local templ - , const char *name - , v8::Handle value -) { - NanSetTemplate(templ->InstanceTemplate(), name, value); -} - -NAN_INLINE void NanSetInstanceTemplate( - v8::Local templ - , v8::Handle name - , v8::Handle value - , v8::PropertyAttribute attributes -) { - NanSetTemplate(templ->InstanceTemplate(), name, value, attributes); -} - -//=== Export ================================================================== - -inline -void -NanExport(v8::Handle target, const char * name, - NanFunctionCallback f) { - target->Set(NanNew(name), - NanNew(f)->GetFunction()); -} - -//=== Tap Reverse Binding ===================================================== - -struct NanTap { - explicit NanTap(v8::Handle t) : t_() { - NanAssignPersistent(t_, t->ToObject()); - } - - ~NanTap() { NanDisposePersistent(t_); } // not sure if neccessary - - inline void plan(int i) { - v8::Handle arg = NanNew(i); - NanMakeCallback(NanNew(t_), "plan", 1, &arg); - } - - inline void ok(bool isOk, const char * msg = NULL) { - v8::Handle args[2]; - args[0] = NanNew(isOk); - if (msg) args[1] = NanNew(msg); - NanMakeCallback(NanNew(t_), "ok", msg ? 2 : 1, args); - } - - private: - v8::Persistent t_; -}; - -#define NAN_STRINGIZE2(x) #x -#define NAN_STRINGIZE(x) NAN_STRINGIZE2(x) -#define NAN_TEST_EXPRESSION(expression) \ - ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression - -#define return_NanValue(v) NanReturnValue(v) -#define return_NanUndefined() NanReturnUndefined() -#define NAN_EXPORT(target, function) NanExport(target, #function, function) - -#endif // NAN_H_ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h deleted file mode 100755 index ff63ec0c..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h +++ /dev/null @@ -1,262 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2015 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_IMPLEMENTATION_12_INL_H_ -#define NAN_IMPLEMENTATION_12_INL_H_ -//============================================================================== -// node v0.11 implementation -//============================================================================== - -#if defined(_MSC_VER) -# pragma warning( disable : 4530 ) -# include -# pragma warning( default : 4530 ) -#else -# include -#endif - -namespace NanIntern { - -//=== Array ==================================================================== - -Factory::return_t -Factory::New() { - return v8::Array::New(v8::Isolate::GetCurrent()); -} - -Factory::return_t -Factory::New(int length) { - return v8::Array::New(v8::Isolate::GetCurrent(), length); -} - -//=== Boolean ================================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::Boolean::New(v8::Isolate::GetCurrent(), value); -} - -//=== Boolean Object =========================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::BooleanObject::New(value).As(); -} - -//=== Context ================================================================== - -Factory::return_t -Factory::New( v8::ExtensionConfiguration* extensions - , v8::Handle tmpl - , v8::Handle obj) { - return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj); -} - -//=== Date ===================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Date::New(v8::Isolate::GetCurrent(), value).As(); -} - -//=== External ================================================================= - -Factory::return_t -Factory::New(void * value) { - return v8::External::New(v8::Isolate::GetCurrent(), value); -} - -//=== Function ================================================================= - -Factory::return_t -Factory::New( NanFunctionCallback callback - , v8::Handle data) { - return v8::Function::New( v8::Isolate::GetCurrent() - , callback - , data); -} - -//=== Function Template ======================================================== - -Factory::return_t -Factory::New( NanFunctionCallback callback - , v8::Handle data - , v8::Handle signature) { - return v8::FunctionTemplate::New( v8::Isolate::GetCurrent() - , callback - , data - , signature); -} - -//=== Number =================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Number::New(v8::Isolate::GetCurrent(), value); -} - -//=== Number Object ============================================================ - -Factory::return_t -Factory::New(double value) { - return v8::NumberObject::New( v8::Isolate::GetCurrent() - , value).As(); -} - -//=== Integer, Int32 and Uint32 ================================================ - -template -typename IntegerFactory::return_t -IntegerFactory::New(int32_t value) { - return To(T::New(v8::Isolate::GetCurrent(), value)); -} - -template -typename IntegerFactory::return_t -IntegerFactory::New(uint32_t value) { - return To(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -Factory::return_t -Factory::New(int32_t value) { - return To( - v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -Factory::return_t -Factory::New(uint32_t value) { - return To( - v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -//=== Object =================================================================== - -Factory::return_t -Factory::New() { - return v8::Object::New(v8::Isolate::GetCurrent()); -} - -//=== Object Template ========================================================== - -Factory::return_t -Factory::New() { - return v8::ObjectTemplate::New(v8::Isolate::GetCurrent()); -} - -//=== RegExp =================================================================== - -Factory::return_t -Factory::New( - v8::Handle pattern - , v8::RegExp::Flags flags) { - return v8::RegExp::New(pattern, flags); -} - -//=== Script =================================================================== - -Factory::return_t -Factory::New( v8::Local source) { - v8::ScriptCompiler::Source src(source); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::ScriptCompiler::Source src(source, origin); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); -} - -//=== Signature ================================================================ - -Factory::return_t -Factory::New( Factory::FTH receiver - , int argc - , Factory::FTH argv[]) { - return v8::Signature::New(v8::Isolate::GetCurrent(), receiver, argc, argv); -} - -//=== String =================================================================== - -Factory::return_t -Factory::New() { - return v8::String::Empty(v8::Isolate::GetCurrent()); -} - -Factory::return_t -Factory::New(const char * value, int length) { - return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New(std::string const& value) { - assert(value.size() <= INT_MAX && "string too long"); - return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), - value.data(), v8::String::kNormalString, static_cast(value.size())); -} - -Factory::return_t -Factory::New(const uint8_t * value, int length) { - return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New(const uint16_t * value, int length) { - return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New(v8::String::ExternalStringResource * value) { - return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); -} - -Factory::return_t -Factory::New(NanExternalOneByteStringResource * value) { - return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); -} - -//=== String Object ============================================================ - -Factory::return_t -Factory::New(v8::Handle value) { - return v8::StringObject::New(value).As(); -} - -//=== Unbound Script =========================================================== - -Factory::return_t -Factory::New(v8::Local source) { - v8::ScriptCompiler::Source src(source); - return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::ScriptCompiler::Source src(source, origin); - return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); -} - -} // end of namespace NanIntern - -//=== Presistents and Handles ================================================== - -template -inline v8::Local NanNew(v8::Handle h) { - return v8::Local::New(v8::Isolate::GetCurrent(), h); -} - -template -inline v8::Local NanNew(v8::Persistent const& p) { - return v8::Local::New(v8::Isolate::GetCurrent(), p); -} - -#endif // NAN_IMPLEMENTATION_12_INL_H_ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h deleted file mode 100755 index 85dd2754..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h +++ /dev/null @@ -1,268 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2015 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_ -#define NAN_IMPLEMENTATION_PRE_12_INL_H_ - -#include - -#if defined(_MSC_VER) -# pragma warning( disable : 4530 ) -# include -# include -# pragma warning( default : 4530 ) -#else -# include -# include -#endif - -//============================================================================== -// node v0.10 implementation -//============================================================================== - -namespace NanIntern { - -//=== Array ==================================================================== - -Factory::return_t -Factory::New() { - return v8::Array::New(); -} - -Factory::return_t -Factory::New(int length) { - return v8::Array::New(length); -} - -//=== Boolean ================================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::Boolean::New(value)->ToBoolean(); -} - -//=== Boolean Object =========================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::BooleanObject::New(value).As(); -} - -//=== Context ================================================================== - -Factory::return_t -Factory::New( v8::ExtensionConfiguration* extensions - , v8::Handle tmpl - , v8::Handle obj) { - v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); - v8::Local lctx = v8::Local::New(ctx); - ctx.Dispose(); - return lctx; -} - -//=== Date ===================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Date::New(value).As(); -} - -//=== External ================================================================= - -Factory::return_t -Factory::New(void * value) { - return v8::External::New(value); -} - -//=== Function ================================================================= - -Factory::return_t -Factory::New( NanFunctionCallback callback - , v8::Handle data) { - return Factory::New( callback - , data - , v8::Handle() - )->GetFunction(); -} - - -//=== FunctionTemplate ========================================================= - -Factory::return_t -Factory::New( NanFunctionCallback callback - , v8::Handle data - , v8::Handle signature) { - // Note(agnat): Emulate length argument here. Unfortunately, I couldn't find - // a way. Have at it though... - return v8::FunctionTemplate::New( callback - , data - , signature); -} - -//=== Number =================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Number::New(value); -} - -//=== Number Object ============================================================ - -Factory::return_t -Factory::New(double value) { - return v8::NumberObject::New(value).As(); -} - -//=== Integer, Int32 and Uint32 ================================================ - -template -typename IntegerFactory::return_t -IntegerFactory::New(int32_t value) { - return To(T::New(value)); -} - -template -typename IntegerFactory::return_t -IntegerFactory::New(uint32_t value) { - return To(T::NewFromUnsigned(value)); -} - -Factory::return_t -Factory::New(int32_t value) { - return To(v8::Uint32::NewFromUnsigned(value)); -} - -Factory::return_t -Factory::New(uint32_t value) { - return To(v8::Uint32::NewFromUnsigned(value)); -} - - -//=== Object =================================================================== - -Factory::return_t -Factory::New() { - return v8::Object::New(); -} - -//=== Object Template ========================================================== - -Factory::return_t -Factory::New() { - return v8::ObjectTemplate::New(); -} - -//=== RegExp =================================================================== - -Factory::return_t -Factory::New( - v8::Handle pattern - , v8::RegExp::Flags flags) { - return v8::RegExp::New(pattern, flags); -} - -//=== Script =================================================================== - -Factory::return_t -Factory::New( v8::Local source) { - return v8::Script::New(source); -} -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - return v8::Script::New(source, const_cast(&origin)); -} - -//=== Signature ================================================================ - -Factory::return_t -Factory::New( Factory::FTH receiver - , int argc - , Factory::FTH argv[]) { - return v8::Signature::New(receiver, argc, argv); -} - -//=== String =================================================================== - -Factory::return_t -Factory::New() { - return v8::String::Empty(); -} - -Factory::return_t -Factory::New(const char * value, int length) { - return v8::String::New(value, length); -} - -Factory::return_t -Factory::New(std::string const& value) { - assert(value.size() <= INT_MAX && "string too long"); - return v8::String::New( value.data(), static_cast(value.size())); -} - -inline -void -widenString(std::vector *ws, const uint8_t *s, int l = -1) { - size_t len = static_cast(l); - if (l < 0) { - len = strlen(reinterpret_cast(s)); - } - assert(len <= INT_MAX && "string too long"); - ws->resize(len); - std::copy(s, s + len, ws->begin()); -} - -Factory::return_t -Factory::New(const uint16_t * value, int length) { - return v8::String::New(value, length); -} - -Factory::return_t -Factory::New(const uint8_t * value, int length) { - std::vector wideString; - widenString(&wideString, value, length); - if (wideString.size() == 0) { - return v8::String::Empty(); - } else { - return v8::String::New(&wideString.front() - , static_cast(wideString.size())); - } -} - -Factory::return_t -Factory::New(v8::String::ExternalStringResource * value) { - return v8::String::NewExternal(value); -} - -Factory::return_t -Factory::New(v8::String::ExternalAsciiStringResource * value) { - return v8::String::NewExternal(value); -} - -//=== String Object ============================================================ - -Factory::return_t -Factory::New(v8::Handle value) { - return v8::StringObject::New(value).As(); -} - -} // end of namespace NanIntern - -//=== Presistents and Handles ================================================== - -template -inline v8::Local NanNew(v8::Handle h) { - return v8::Local::New(h); -} - -template -inline v8::Local NanNew(v8::Persistent const& p) { - return v8::Local::New(p); -} - -#endif // NAN_IMPLEMENTATION_PRE_12_INL_H_ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_new.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_new.h deleted file mode 100755 index 95b6b51e..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_new.h +++ /dev/null @@ -1,329 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2015 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_NEW_H_ -#define NAN_NEW_H_ - -#if defined(_MSC_VER) -# pragma warning( disable : 4530 ) -# include -# pragma warning( default : 4530 ) -#else -# include -#endif - -namespace NanIntern { // scnr - -// TODO(agnat): Generalize -template v8::Local To(v8::Handle i); - -template <> -inline -v8::Local -To(v8::Handle i) { return i->ToInteger(); } - -template <> -inline -v8::Local -To(v8::Handle i) { return i->ToInt32(); } - -template <> -inline -v8::Local -To(v8::Handle i) { return i->ToUint32(); } - -template struct FactoryBase { typedef v8::Local return_t; }; - -template struct Factory; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); - static inline return_t New(int length); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(bool value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(bool value); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle()); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(void *value); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( NanFunctionCallback callback - , v8::Handle data = v8::Handle()); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( NanFunctionCallback callback = NULL - , v8::Handle data = v8::Handle() - , v8::Handle signature = v8::Handle()); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template -struct IntegerFactory : FactoryBase { - typedef typename FactoryBase::return_t return_t; - static inline return_t New(int32_t value); - static inline return_t New(uint32_t value); -}; - -template <> -struct Factory : IntegerFactory {}; - -template <> -struct Factory : IntegerFactory {}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(int32_t value); - static inline return_t New(uint32_t value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New( - v8::Handle pattern, v8::RegExp::Flags flags); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New( v8::Local source); - static inline return_t New( v8::Local source - , v8::ScriptOrigin const& origin); -}; - -template <> -struct Factory : FactoryBase { - typedef v8::Handle FTH; - static inline - return_t - New( FTH receiver = FTH(), int argc = 0, FTH argv[] = NULL ); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); - static inline return_t New(const char *value, int length = -1); - static inline return_t New(const uint16_t *value, int length = -1); - static inline return_t New(std::string const& value); - - static inline return_t New(v8::String::ExternalStringResource * value); - static inline return_t New(NanExternalOneByteStringResource * value); - - // TODO(agnat): Deprecate. - static inline return_t New(const uint8_t * value, int length = -1); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(v8::Handle value); -}; - -} // end of namespace NanIntern - -#if (NODE_MODULE_VERSION >= 12) - -namespace NanIntern { - -template <> -struct Factory : FactoryBase { - static inline return_t New( v8::Local source); - static inline return_t New( v8::Local source - , v8::ScriptOrigin const& origin); -}; - -} // end of namespace NanIntern - -# include "nan_implementation_12_inl.h" - -#else // NODE_MODULE_VERSION >= 12 - -# include "nan_implementation_pre_12_inl.h" - -#endif - -//=== API ====================================================================== - -template -typename NanIntern::Factory::return_t -NanNew() { - return NanIntern::Factory::New(); -} - -template -typename NanIntern::Factory::return_t -NanNew(A0 arg0) { - return NanIntern::Factory::New(arg0); -} - -template -typename NanIntern::Factory::return_t -NanNew(A0 arg0, A1 arg1) { - return NanIntern::Factory::New(arg0, arg1); -} - -template -typename NanIntern::Factory::return_t -NanNew(A0 arg0, A1 arg1, A2 arg2) { - return NanIntern::Factory::New(arg0, arg1, arg2); -} - -template -typename NanIntern::Factory::return_t -NanNew(A0 arg0, A1 arg1, A2 arg2, A3 arg3) { - return NanIntern::Factory::New(arg0, arg1, arg2, arg3); -} - -// Note(agnat): When passing overloaded function pointers to template functions -// as generic arguments the compiler needs help in picking the right overload. -// These two functions handle NanNew and NanNew with -// all argument variations. - -// v8::Function and v8::FunctionTemplate with one or two arguments -template -typename NanIntern::Factory::return_t -NanNew( NanFunctionCallback callback - , v8::Handle data = v8::Handle()) { - return NanIntern::Factory::New(callback, data); -} - -// v8::Function and v8::FunctionTemplate with three arguments -template -typename NanIntern::Factory::return_t -NanNew( NanFunctionCallback callback - , v8::Handle data = v8::Handle() - , A2 a2 = A2()) { - return NanIntern::Factory::New(callback, data, a2); -} - -// Convenience - -template inline v8::Local NanNew(v8::Handle h); -template inline v8::Local NanNew(v8::Persistent const& p); - -inline -NanIntern::Factory::return_t -NanNew(bool value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(int32_t value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(uint32_t value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(double value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(std::string const& value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(const char * value, int length) { - return NanNew(value, length); -} - -inline -NanIntern::Factory::return_t -NanNew(const char * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(const uint8_t * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(const uint16_t * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(v8::String::ExternalStringResource * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(NanExternalOneByteStringResource * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(v8::Handle pattern, v8::RegExp::Flags flags) { - return NanNew(pattern, flags); -} - -#endif // NAN_NEW_H_ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_string_bytes.h b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_string_bytes.h deleted file mode 100755 index 9deecfbb..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_string_bytes.h +++ /dev/null @@ -1,312 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -#ifndef NAN_STRING_BYTES_H_ -#define NAN_STRING_BYTES_H_ - -// Decodes a v8::Handle or Buffer to a raw char* - -#include -#include -#include -#include // memcpy -#include - -namespace NanIntern { - -using v8::Local; -using v8::Handle; -using v8::Object; -using v8::String; -using v8::Value; - - -//// Base 64 //// - -#define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) - - - -//// Nan::HEX //// - -static bool contains_non_ascii_slow(const char* buf, size_t len) { - for (size_t i = 0; i < len; ++i) { - if (buf[i] & 0x80) return true; - } - return false; -} - - -static bool contains_non_ascii(const char* src, size_t len) { - if (len < 16) { - return contains_non_ascii_slow(src, len); - } - - const unsigned bytes_per_word = sizeof(void*); - const unsigned align_mask = bytes_per_word - 1; - const unsigned unaligned = reinterpret_cast(src) & align_mask; - - if (unaligned > 0) { - const unsigned n = bytes_per_word - unaligned; - if (contains_non_ascii_slow(src, n)) return true; - src += n; - len -= n; - } - - -#if defined(__x86_64__) || defined(_WIN64) - const uintptr_t mask = 0x8080808080808080ll; -#else - const uintptr_t mask = 0x80808080l; -#endif - - const uintptr_t* srcw = reinterpret_cast(src); - - for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { - if (srcw[i] & mask) return true; - } - - const unsigned remainder = len & align_mask; - if (remainder > 0) { - const size_t offset = len - remainder; - if (contains_non_ascii_slow(src + offset, remainder)) return true; - } - - return false; -} - - -static void force_ascii_slow(const char* src, char* dst, size_t len) { - for (size_t i = 0; i < len; ++i) { - dst[i] = src[i] & 0x7f; - } -} - - -static void force_ascii(const char* src, char* dst, size_t len) { - if (len < 16) { - force_ascii_slow(src, dst, len); - return; - } - - const unsigned bytes_per_word = sizeof(void*); - const unsigned align_mask = bytes_per_word - 1; - const unsigned src_unalign = reinterpret_cast(src) & align_mask; - const unsigned dst_unalign = reinterpret_cast(dst) & align_mask; - - if (src_unalign > 0) { - if (src_unalign == dst_unalign) { - const unsigned unalign = bytes_per_word - src_unalign; - force_ascii_slow(src, dst, unalign); - src += unalign; - dst += unalign; - len -= src_unalign; - } else { - force_ascii_slow(src, dst, len); - return; - } - } - -#if defined(__x86_64__) || defined(_WIN64) - const uintptr_t mask = ~0x8080808080808080ll; -#else - const uintptr_t mask = ~0x80808080l; -#endif - - const uintptr_t* srcw = reinterpret_cast(src); - uintptr_t* dstw = reinterpret_cast(dst); - - for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { - dstw[i] = srcw[i] & mask; - } - - const unsigned remainder = len & align_mask; - if (remainder > 0) { - const size_t offset = len - remainder; - force_ascii_slow(src + offset, dst + offset, remainder); - } -} - - -static size_t base64_encode(const char* src, - size_t slen, - char* dst, - size_t dlen) { - // We know how much we'll write, just make sure that there's space. - assert(dlen >= base64_encoded_size(slen) && - "not enough space provided for base64 encode"); - - dlen = base64_encoded_size(slen); - - unsigned a; - unsigned b; - unsigned c; - unsigned i; - unsigned k; - unsigned n; - - static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - - i = 0; - k = 0; - n = slen / 3 * 3; - - while (i < n) { - a = src[i + 0] & 0xff; - b = src[i + 1] & 0xff; - c = src[i + 2] & 0xff; - - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; - dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)]; - dst[k + 3] = table[c & 0x3f]; - - i += 3; - k += 4; - } - - if (n != slen) { - switch (slen - n) { - case 1: - a = src[i + 0] & 0xff; - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[(a & 3) << 4]; - dst[k + 2] = '='; - dst[k + 3] = '='; - break; - - case 2: - a = src[i + 0] & 0xff; - b = src[i + 1] & 0xff; - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; - dst[k + 2] = table[(b & 0x0f) << 2]; - dst[k + 3] = '='; - break; - } - } - - return dlen; -} - - -static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) { - // We know how much we'll write, just make sure that there's space. - assert(dlen >= slen * 2 && - "not enough space provided for hex encode"); - - dlen = slen * 2; - for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) { - static const char hex[] = "0123456789abcdef"; - uint8_t val = static_cast(src[i]); - dst[k + 0] = hex[val >> 4]; - dst[k + 1] = hex[val & 15]; - } - - return dlen; -} - - - -static Local Encode(const char* buf, - size_t buflen, - enum Nan::Encoding encoding) { - assert(buflen <= node::Buffer::kMaxLength); - if (!buflen && encoding != Nan::BUFFER) - return NanNew(""); - - Local val; - switch (encoding) { - case Nan::BUFFER: - return NanNewBufferHandle(buf, buflen); - - case Nan::ASCII: - if (contains_non_ascii(buf, buflen)) { - char* out = new char[buflen]; - force_ascii(buf, out, buflen); - val = NanNew(out, buflen); - delete[] out; - } else { - val = NanNew(buf, buflen); - } - break; - - case Nan::UTF8: - val = NanNew(buf, buflen); - break; - - case Nan::BINARY: { - // TODO(isaacs) use ExternalTwoByteString? - const unsigned char *cbuf = reinterpret_cast(buf); - uint16_t * twobytebuf = new uint16_t[buflen]; - for (size_t i = 0; i < buflen; i++) { - // XXX is the following line platform independent? - twobytebuf[i] = cbuf[i]; - } - val = NanNew(twobytebuf, buflen); - delete[] twobytebuf; - break; - } - - case Nan::BASE64: { - size_t dlen = base64_encoded_size(buflen); - char* dst = new char[dlen]; - - size_t written = base64_encode(buf, buflen, dst, dlen); - assert(written == dlen); - - val = NanNew(dst, dlen); - delete[] dst; - break; - } - - case Nan::UCS2: { - const uint16_t* data = reinterpret_cast(buf); - val = NanNew(data, buflen / 2); - break; - } - - case Nan::HEX: { - size_t dlen = buflen * 2; - char* dst = new char[dlen]; - size_t written = hex_encode(buf, buflen, dst, dlen); - assert(written == dlen); - - val = NanNew(dst, dlen); - delete[] dst; - break; - } - - default: - assert(0 && "unknown encoding"); - break; - } - - return val; -} - -#undef base64_encoded_size - -} // namespace NanIntern - -#endif // NAN_STRING_BYTES_H_ diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/package.json b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/package.json deleted file mode 100755 index 63259da1..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/node_modules/nan/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "name": "nan", - "version": "1.6.2", - "description": "Native Abstractions for Node.js: C++ header for Node 0.8->0.12 compatibility", - "main": "include_dirs.js", - "repository": { - "type": "git", - "url": "git://github.com/rvagg/nan.git" - }, - "scripts": { - "test": "tap --gc test/js/*-test.js", - "rebuild-tests": "pangyp rebuild --directory test" - }, - "contributors": [ - { - "name": "Rod Vagg", - "email": "r@va.gg", - "url": "https://github.com/rvagg" - }, - { - "name": "Benjamin Byholm", - "email": "bbyholm@abo.fi", - "url": "https://github.com/kkoopa/" - }, - { - "name": "Trevor Norris", - "email": "trev.norris@gmail.com", - "url": "https://github.com/trevnorris" - }, - { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "https://github.com/TooTallNate" - }, - { - "name": "Brett Lawson", - "email": "brett19@gmail.com", - "url": "https://github.com/brett19" - }, - { - "name": "Ben Noordhuis", - "email": "info@bnoordhuis.nl", - "url": "https://github.com/bnoordhuis" - }, - { - "name": "David Siegel", - "email": "david@artcom.de", - "url": "https://github.com/agnat" - } - ], - "devDependencies": { - "bindings": "~1.2.1", - "node-gyp": "~1.0.2", - "pangyp": "~2.0.1", - "tap": "~0.5.0", - "xtend": "~4.0.0" - }, - "license": "MIT", - "gitHead": "ab0e5eed8d4aa36111bf8f44cf75644ece327e98", - "bugs": { - "url": "https://github.com/rvagg/nan/issues" - }, - "homepage": "https://github.com/rvagg/nan", - "_id": "nan@1.6.2", - "_shasum": "2657d1c43b00f1e847e083832285b7d8f5ba8ec8", - "_from": "nan@1.6.2", - "_npmVersion": "2.0.0", - "_npmUser": { - "name": "kkoopa", - "email": "bbyholm@abo.fi" - }, - "maintainers": [ - { - "name": "rvagg", - "email": "rod@vagg.org" - }, - { - "name": "kkoopa", - "email": "bbyholm@abo.fi" - } - ], - "dist": { - "shasum": "2657d1c43b00f1e847e083832285b7d8f5ba8ec8", - "tarball": "http://registry.npmjs.org/nan/-/nan-1.6.2.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/nan/-/nan-1.6.2.tgz" -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/package.json b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/package.json deleted file mode 100755 index 92472176..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "kerberos", - "version": "0.0.9", - "description": "Kerberos library for Node.js", - "main": "index.js", - "repository": { - "type": "git", - "url": "https://github.com/christkv/kerberos.git" - }, - "keywords": [ - "kerberos", - "security", - "authentication" - ], - "dependencies": { - "nan": "1.6.2" - }, - "devDependencies": { - "nodeunit": "latest" - }, - "scripts": { - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "nodeunit ./test" - }, - "author": { - "name": "Christian Amor Kvalheim" - }, - "license": "Apache 2.0", - "gitHead": "bb01d4fe322e022999aca19da564e7d9db59a8ed", - "bugs": { - "url": "https://github.com/christkv/kerberos/issues" - }, - "homepage": "https://github.com/christkv/kerberos", - "_id": "kerberos@0.0.9", - "_shasum": "595bf97e7e8aae5401ae313aea57bbf402e799c5", - "_from": "kerberos@0.0.9", - "_npmVersion": "2.5.1", - "_nodeVersion": "0.12.0", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "maintainers": [ - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "595bf97e7e8aae5401ae313aea57bbf402e799c5", - "tarball": "http://registry.npmjs.org/kerberos/-/kerberos-0.0.9.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/kerberos/-/kerberos-0.0.9.tgz" -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js deleted file mode 100755 index a06c5fdf..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js +++ /dev/null @@ -1,34 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Simple initialize of Kerberos object'] = function(test) { - var Kerberos = require('../lib/kerberos.js').Kerberos; - var kerberos = new Kerberos(); - // console.dir(kerberos) - - // Initiate kerberos client - kerberos.authGSSClientInit('mongodb@kdc.10gen.me', Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - console.log("===================================== authGSSClientInit") - test.equal(null, err); - test.ok(context != null && typeof context == 'object'); - // console.log("===================================== authGSSClientInit") - console.dir(err) - console.dir(context) - // console.dir(typeof result) - - // Perform the first step - kerberos.authGSSClientStep(context, function(err, result) { - console.log("===================================== authGSSClientStep") - console.dir(err) - console.dir(result) - console.dir(context) - - test.done(); - }); - }); -} \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js deleted file mode 100755 index d2f70463..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js +++ /dev/null @@ -1,19 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Simple initialize of Kerberos win32 object'] = function(test) { - var KerberosNative = require('../build/Release/kerberos').Kerberos; - // console.dir(KerberosNative) - var kerberos = new KerberosNative(); - console.log("=========================================== 0") - console.dir(kerberos.acquireAlternateCredentials("dev1@10GEN.ME", "a")); - console.log("=========================================== 1") - console.dir(kerberos.prepareOutboundPackage("mongodb/kdc.10gen.com")); - console.log("=========================================== 2") - test.done(); -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js deleted file mode 100755 index 3531b6bc..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js +++ /dev/null @@ -1,41 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer Descriptor'] = function(test) { - var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // Create descriptor with single Buffer - var securityDescriptor = new SecurityBufferDescriptor(100); - try { - // Fail to work due to no valid Security Buffer - securityDescriptor = new SecurityBufferDescriptor(["hello"]); - test.ok(false); - } catch(err){} - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - // Should correctly return a buffer - var result = securityDescriptor.toBuffer(); - test.equal(100, result.length); - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - var result = securityDescriptor.toBuffer(); - test.equal("hello world", result.toString()); - - // Test passing in more than one Buffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - var result = securityDescriptor.toBuffer(); - test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js deleted file mode 100755 index b52b9598..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js +++ /dev/null @@ -1,22 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer'] = function(test) { - var SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - // Create empty buffer - var securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - var buffer = securityBuffer.toBuffer(); - test.equal(100, buffer.length); - - // Access data passed in - var allocated_buffer = new Buffer(256); - securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, allocated_buffer); - buffer = securityBuffer.toBuffer(); - test.deepEqual(allocated_buffer, buffer); - test.done(); -} \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js b/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js deleted file mode 100755 index 77581800..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js +++ /dev/null @@ -1,55 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a set of security credentials'] = function(test) { - var SecurityCredentials = require('../../lib/sspi.js').SecurityCredentials; - - // Aquire some credentials - try { - var credentials = SecurityCredentials.aquire('Kerberos', 'dev1@10GEN.ME', 'a'); - } catch(err) { - console.dir(err) - test.ok(false); - } - - - - // console.dir(SecurityCredentials); - - // var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - // SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // // Create descriptor with single Buffer - // var securityDescriptor = new SecurityBufferDescriptor(100); - // try { - // // Fail to work due to no valid Security Buffer - // securityDescriptor = new SecurityBufferDescriptor(["hello"]); - // test.ok(false); - // } catch(err){} - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // // Should correctly return a buffer - // var result = securityDescriptor.toBuffer(); - // test.equal(100, result.length); - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello world", result.toString()); - - // // Test passing in more than one Buffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - // securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/.npmignore b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/.npmignore deleted file mode 100755 index 38344f87..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -build/ -test/ -examples/ -fs.js -zlib.js \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/LICENSE b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/LICENSE deleted file mode 100755 index e3d4e695..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/README.md b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/README.md deleted file mode 100755 index 3fb3e802..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# readable-stream - -***Node-core streams for userland*** - -[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) -[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) - -This package is a mirror of the Streams2 and Streams3 implementations in Node-core. - -If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core. - -**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12. - -**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"` - diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/duplex.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/duplex.js deleted file mode 100755 index ca807af8..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/duplex.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_duplex.js") diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js deleted file mode 100755 index b513d61a..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - -module.exports = Duplex; - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -} -/**/ - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); - -util.inherits(Duplex, Readable); - -forEach(objectKeys(Writable.prototype), function(method) { - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; -}); - -function Duplex(options) { - if (!(this instanceof Duplex)) - return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) - this.readable = false; - - if (options && options.writable === false) - this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; - - this.once('end', onend); -} - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) - return; - - // no more data can be written. - // But allow more writes to happen in this tick. - process.nextTick(this.end.bind(this)); -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js deleted file mode 100755 index 895ca50a..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); - - Transform.call(this, options); -} - -PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); -}; diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js deleted file mode 100755 index 63072209..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js +++ /dev/null @@ -1,982 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -module.exports = Readable; - -/**/ -var isArray = require('isarray'); -/**/ - - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Readable.ReadableState = ReadableState; - -var EE = require('events').EventEmitter; - -/**/ -if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -var Stream = require('stream'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var StringDecoder; - -util.inherits(Readable, Stream); - -function ReadableState(options, stream) { - options = options || {}; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = false; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // In streams that never have any data, and do push(null) right away, - // the consumer can miss the 'end' event if they do some I/O before - // consuming the stream. So, we don't emit('end') until some reading - // happens. - this.calledRead = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) - StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - if (!(this instanceof Readable)) - return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - Stream.call(this); -} - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function(chunk, encoding) { - var state = this._readableState; - - if (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer(chunk, encoding); - encoding = ''; - } - } - - return readableAddChunk(this, state, chunk, encoding, false); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; - -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null || chunk === undefined) { - state.reading = false; - if (!state.ended) - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var e = new Error('stream.unshift() after end event'); - stream.emit('error', e); - } else { - if (state.decoder && !addToFront && !encoding) - chunk = state.decoder.write(chunk); - - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) { - state.buffer.unshift(chunk); - } else { - state.reading = false; - state.buffer.push(chunk); - } - - if (state.needReadable) - emitReadable(stream); - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); -} - - - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && - (state.needReadable || - state.length < state.highWaterMark || - state.length === 0); -} - -// backwards compatibility. -Readable.prototype.setEncoding = function(enc) { - if (!StringDecoder) - StringDecoder = require('string_decoder/').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; -}; - -// Don't raise the hwm > 128MB -var MAX_HWM = 0x800000; -function roundUpToNextPowerOf2(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 - n--; - for (var p = 1; p < 32; p <<= 1) n |= n >> p; - n++; - } - return n; -} - -function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; - - if (state.objectMode) - return n === 0 ? 0 : 1; - - if (n === null || isNaN(n)) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; - else - return state.length; - } - - if (n <= 0) - return 0; - - // If we're asking for more than the target buffer level, - // then raise the water mark. Bump up to the next highest - // power of 2, to prevent increasing it excessively in tiny - // amounts. - if (n > state.highWaterMark) - state.highWaterMark = roundUpToNextPowerOf2(n); - - // don't have that much. return null, unless we've ended. - if (n > state.length) { - if (!state.ended) { - state.needReadable = true; - return 0; - } else - return state.length; - } - - return n; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function(n) { - var state = this._readableState; - state.calledRead = true; - var nOrig = n; - var ret; - - if (typeof n !== 'number' || n > 0) - state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && - state.needReadable && - (state.length >= state.highWaterMark || state.ended)) { - emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - ret = null; - - // In cases where the decoder did not receive enough data - // to produce a full chunk, then immediately received an - // EOF, state.buffer will contain [, ]. - // howMuchToRead will see this and coerce the amount to - // read to zero (because it's looking at the length of the - // first in state.buffer), and we'll end up here. - // - // This can only happen via state.decoder -- no other venue - // exists for pushing a zero-length chunk into state.buffer - // and triggering this behavior. In this case, we return our - // remaining data and end the stream, if appropriate. - if (state.length > 0 && state.decoder) { - ret = fromList(n, state); - state.length -= ret.length; - } - - if (state.length === 0) - endReadable(this); - - return ret; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - - // if we currently have less than the highWaterMark, then also read some - if (state.length - n <= state.highWaterMark) - doRead = true; - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) - doRead = false; - - if (doRead) { - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) - state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - } - - // If _read called its callback synchronously, then `reading` - // will be false, and we need to re-evaluate how much data we - // can return to the user. - if (doRead && !state.reading) - n = howMuchToRead(nOrig, state); - - if (n > 0) - ret = fromList(n, state); - else - ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } - - state.length -= n; - - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (state.length === 0 && !state.ended) - state.needReadable = true; - - // If we happened to read() exactly the remaining amount in the - // buffer, and the EOF has been seen at this point, then make sure - // that we emit 'end' on the very next tick. - if (state.ended && !state.endEmitted && state.length === 0) - endReadable(this); - - return ret; -}; - -function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - - -function onEofChunk(stream, state) { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // if we've ended and we have some data left, then emit - // 'readable' now to make sure it gets picked up. - if (state.length > 0) - emitReadable(stream); - else - endReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (state.emittedReadable) - return; - - state.emittedReadable = true; - if (state.sync) - process.nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); -} - -function emitReadable_(stream) { - stream.emit('readable'); -} - - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(function() { - maybeReadMore_(stream, state); - }); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else - len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function(n) { - this.emit('error', new Error('not implemented')); -}; - -Readable.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - process.nextTick(endFn); - else - src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - if (readable !== src) return; - cleanup(); - } - - function onend() { - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - function cleanup() { - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (!dest._writableState || dest._writableState.needDrain) - ondrain(); - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - unpipe(); - dest.removeListener('error', onerror); - if (EE.listenerCount(dest, 'error') === 0) - dest.emit('error', er); - } - // This is a brutally ugly hack to make sure that our error handler - // is attached before any userland ones. NEVER DO THIS. - if (!dest._events || !dest._events.error) - dest.on('error', onerror); - else if (isArray(dest._events.error)) - dest._events.error.unshift(onerror); - else - dest._events.error = [onerror, dest._events.error]; - - - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - // the handler that waits for readable events after all - // the data gets sucked out in flow. - // This would be easier to follow with a .once() handler - // in flow(), but that is too slow. - this.on('readable', pipeOnReadable); - - state.flowing = true; - process.nextTick(function() { - flow(src); - }); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function() { - var dest = this; - var state = src._readableState; - state.awaitDrain--; - if (state.awaitDrain === 0) - flow(src); - }; -} - -function flow(src) { - var state = src._readableState; - var chunk; - state.awaitDrain = 0; - - function write(dest, i, list) { - var written = dest.write(chunk); - if (false === written) { - state.awaitDrain++; - } - } - - while (state.pipesCount && null !== (chunk = src.read())) { - - if (state.pipesCount === 1) - write(state.pipes, 0, null); - else - forEach(state.pipes, write); - - src.emit('data', chunk); - - // if anyone needs a drain, then we have to wait for that. - if (state.awaitDrain > 0) - return; - } - - // if every destination was unpiped, either before entering this - // function, or in the while loop, then stop flowing. - // - // NB: This is a pretty rare edge case. - if (state.pipesCount === 0) { - state.flowing = false; - - // if there were data event listeners added, then switch to old mode. - if (EE.listenerCount(src, 'data') > 0) - emitDataEvents(src); - return; - } - - // at this point, no one needed a drain, so we just ran out of data - // on the next readable event, start it over again. - state.ranOut = true; -} - -function pipeOnReadable() { - if (this._readableState.ranOut) { - this._readableState.ranOut = false; - flow(this); - } -} - - -Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) - return this; - - if (!dest) - dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } - - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function(ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - if (ev === 'data' && !this._readableState.flowing) - emitDataEvents(this); - - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - this.read(0); - } else if (state.length) { - emitReadable(this, state); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function() { - emitDataEvents(this); - this.read(0); - this.emit('resume'); -}; - -Readable.prototype.pause = function() { - emitDataEvents(this, true); - this.emit('pause'); -}; - -function emitDataEvents(stream, startPaused) { - var state = stream._readableState; - - if (state.flowing) { - // https://github.com/isaacs/readable-stream/issues/16 - throw new Error('Cannot switch to old mode now.'); - } - - var paused = startPaused || false; - var readable = false; - - // convert to an old-style stream. - stream.readable = true; - stream.pipe = Stream.prototype.pipe; - stream.on = stream.addListener = Stream.prototype.on; - - stream.on('readable', function() { - readable = true; - - var c; - while (!paused && (null !== (c = stream.read()))) - stream.emit('data', c); - - if (c === null) { - readable = false; - stream._readableState.needReadable = true; - } - }); - - stream.pause = function() { - paused = true; - this.emit('pause'); - }; - - stream.resume = function() { - paused = false; - if (readable) - process.nextTick(function() { - stream.emit('readable'); - }); - else - this.read(0); - this.emit('resume'); - }; - - // now make it start, just in case it hadn't already. - stream.emit('readable'); -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function() { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function(chunk) { - if (state.decoder) - chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - //if (state.objectMode && util.isNullOrUndefined(chunk)) - if (state.objectMode && (chunk === null || chunk === undefined)) - return; - else if (!state.objectMode && (!chunk || !chunk.length)) - return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (typeof stream[i] === 'function' && - typeof this[i] === 'undefined') { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); - } - } - - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function(ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; -}; - - - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; - - // nothing in the list, definitely empty. - if (list.length === 0) - return null; - - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer.concat(list, length); - list.length = 0; - } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer(n); - - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); - - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); - - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); - - c += cpy; - } - } - } - - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('endReadable called on non-empty stream'); - - if (!state.endEmitted && state.calledRead) { - state.ended = true; - process.nextTick(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); - } -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js deleted file mode 100755 index eb188df3..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - -module.exports = Transform; - -var Duplex = require('./_stream_duplex'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(Transform, Duplex); - - -function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (data !== null && data !== undefined) - stream.push(data); - - if (cb) - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} - - -function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); - - Duplex.call(this, options); - - var ts = this._transformState = new TransformState(options, this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - this.once('finish', function() { - if ('function' === typeof this._flush) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); -} - -Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function(chunk, encoding, cb) { - throw new Error('not implemented'); -}; - -Transform.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); - } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function(n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - - -function done(stream, er) { - if (er) - return stream.emit('error', er); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var rs = stream._readableState; - var ts = stream._transformState; - - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); - - if (ts.transforming) - throw new Error('calling transform done when still transforming'); - - return stream.push(null); -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js deleted file mode 100755 index 4bdaa4fa..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js +++ /dev/null @@ -1,386 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, cb), and it'll handle all -// the drain event emission and buffering. - -module.exports = Writable; - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Writable.WritableState = WritableState; - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Stream = require('stream'); - -util.inherits(Writable, Stream); - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; -} - -function WritableState(options, stream) { - options = options || {}; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.buffer = []; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; -} - -function Writable(options) { - var Duplex = require('./_stream_duplex'); - - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) - return new Writable(options); - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); -}; - - -function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); -} - -// If we get something that is not a buffer, string, null, or undefined, -// and we're not in objectMode, then that's an error. -// Otherwise stream chunks are all considered to be of length=1, and the -// watermarks determine how many objects to keep in the buffer, rather than -// how many bytes or characters. -function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); - valid = false; - } - return valid; -} - -Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; - - if (typeof cb !== 'function') - cb = function() {}; - - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); - - return ret; -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer(chunk, encoding); - } - return chunk; -} - -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; - - if (state.writing) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); - - return ret; -} - -function doWrite(stream, state, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - if (sync) - process.nextTick(function() { - cb(er); - }); - else - cb(er); - - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) - onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(stream, state); - - if (!finished && !state.bufferProcessing && state.buffer.length) - clearBuffer(stream, state); - - if (sync) { - process.nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - cb(); - if (finished) - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, len, chunk, encoding, cb); - - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - c++; - break; - } - } - - state.bufferProcessing = false; - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; -} - -Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); -}; - -Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (typeof chunk !== 'undefined' && chunk !== null) - this.write(chunk, encoding); - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); -}; - - -function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); -} - -function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - state.finished = true; - stream.emit('finish'); - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - process.nextTick(cb); - else - stream.once('finish', cb); - } - state.ended = true; -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md deleted file mode 100755 index 5a76b414..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# core-util-is - -The `util.is*` functions introduced in Node v0.12. diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch deleted file mode 100755 index a06d5c05..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch +++ /dev/null @@ -1,604 +0,0 @@ -diff --git a/lib/util.js b/lib/util.js -index a03e874..9074e8e 100644 ---- a/lib/util.js -+++ b/lib/util.js -@@ -19,430 +19,6 @@ - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - --var formatRegExp = /%[sdj%]/g; --exports.format = function(f) { -- if (!isString(f)) { -- var objects = []; -- for (var i = 0; i < arguments.length; i++) { -- objects.push(inspect(arguments[i])); -- } -- return objects.join(' '); -- } -- -- var i = 1; -- var args = arguments; -- var len = args.length; -- var str = String(f).replace(formatRegExp, function(x) { -- if (x === '%%') return '%'; -- if (i >= len) return x; -- switch (x) { -- case '%s': return String(args[i++]); -- case '%d': return Number(args[i++]); -- case '%j': -- try { -- return JSON.stringify(args[i++]); -- } catch (_) { -- return '[Circular]'; -- } -- default: -- return x; -- } -- }); -- for (var x = args[i]; i < len; x = args[++i]) { -- if (isNull(x) || !isObject(x)) { -- str += ' ' + x; -- } else { -- str += ' ' + inspect(x); -- } -- } -- return str; --}; -- -- --// Mark that a method should not be used. --// Returns a modified function which warns once by default. --// If --no-deprecation is set, then it is a no-op. --exports.deprecate = function(fn, msg) { -- // Allow for deprecating things in the process of starting up. -- if (isUndefined(global.process)) { -- return function() { -- return exports.deprecate(fn, msg).apply(this, arguments); -- }; -- } -- -- if (process.noDeprecation === true) { -- return fn; -- } -- -- var warned = false; -- function deprecated() { -- if (!warned) { -- if (process.throwDeprecation) { -- throw new Error(msg); -- } else if (process.traceDeprecation) { -- console.trace(msg); -- } else { -- console.error(msg); -- } -- warned = true; -- } -- return fn.apply(this, arguments); -- } -- -- return deprecated; --}; -- -- --var debugs = {}; --var debugEnviron; --exports.debuglog = function(set) { -- if (isUndefined(debugEnviron)) -- debugEnviron = process.env.NODE_DEBUG || ''; -- set = set.toUpperCase(); -- if (!debugs[set]) { -- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { -- var pid = process.pid; -- debugs[set] = function() { -- var msg = exports.format.apply(exports, arguments); -- console.error('%s %d: %s', set, pid, msg); -- }; -- } else { -- debugs[set] = function() {}; -- } -- } -- return debugs[set]; --}; -- -- --/** -- * Echos the value of a value. Trys to print the value out -- * in the best way possible given the different types. -- * -- * @param {Object} obj The object to print out. -- * @param {Object} opts Optional options object that alters the output. -- */ --/* legacy: obj, showHidden, depth, colors*/ --function inspect(obj, opts) { -- // default options -- var ctx = { -- seen: [], -- stylize: stylizeNoColor -- }; -- // legacy... -- if (arguments.length >= 3) ctx.depth = arguments[2]; -- if (arguments.length >= 4) ctx.colors = arguments[3]; -- if (isBoolean(opts)) { -- // legacy... -- ctx.showHidden = opts; -- } else if (opts) { -- // got an "options" object -- exports._extend(ctx, opts); -- } -- // set default options -- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; -- if (isUndefined(ctx.depth)) ctx.depth = 2; -- if (isUndefined(ctx.colors)) ctx.colors = false; -- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; -- if (ctx.colors) ctx.stylize = stylizeWithColor; -- return formatValue(ctx, obj, ctx.depth); --} --exports.inspect = inspect; -- -- --// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics --inspect.colors = { -- 'bold' : [1, 22], -- 'italic' : [3, 23], -- 'underline' : [4, 24], -- 'inverse' : [7, 27], -- 'white' : [37, 39], -- 'grey' : [90, 39], -- 'black' : [30, 39], -- 'blue' : [34, 39], -- 'cyan' : [36, 39], -- 'green' : [32, 39], -- 'magenta' : [35, 39], -- 'red' : [31, 39], -- 'yellow' : [33, 39] --}; -- --// Don't use 'blue' not visible on cmd.exe --inspect.styles = { -- 'special': 'cyan', -- 'number': 'yellow', -- 'boolean': 'yellow', -- 'undefined': 'grey', -- 'null': 'bold', -- 'string': 'green', -- 'date': 'magenta', -- // "name": intentionally not styling -- 'regexp': 'red' --}; -- -- --function stylizeWithColor(str, styleType) { -- var style = inspect.styles[styleType]; -- -- if (style) { -- return '\u001b[' + inspect.colors[style][0] + 'm' + str + -- '\u001b[' + inspect.colors[style][1] + 'm'; -- } else { -- return str; -- } --} -- -- --function stylizeNoColor(str, styleType) { -- return str; --} -- -- --function arrayToHash(array) { -- var hash = {}; -- -- array.forEach(function(val, idx) { -- hash[val] = true; -- }); -- -- return hash; --} -- -- --function formatValue(ctx, value, recurseTimes) { -- // Provide a hook for user-specified inspect functions. -- // Check that value is an object with an inspect function on it -- if (ctx.customInspect && -- value && -- isFunction(value.inspect) && -- // Filter out the util module, it's inspect function is special -- value.inspect !== exports.inspect && -- // Also filter out any prototype objects using the circular check. -- !(value.constructor && value.constructor.prototype === value)) { -- var ret = value.inspect(recurseTimes, ctx); -- if (!isString(ret)) { -- ret = formatValue(ctx, ret, recurseTimes); -- } -- return ret; -- } -- -- // Primitive types cannot have properties -- var primitive = formatPrimitive(ctx, value); -- if (primitive) { -- return primitive; -- } -- -- // Look up the keys of the object. -- var keys = Object.keys(value); -- var visibleKeys = arrayToHash(keys); -- -- if (ctx.showHidden) { -- keys = Object.getOwnPropertyNames(value); -- } -- -- // Some type of object without properties can be shortcutted. -- if (keys.length === 0) { -- if (isFunction(value)) { -- var name = value.name ? ': ' + value.name : ''; -- return ctx.stylize('[Function' + name + ']', 'special'); -- } -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } -- if (isDate(value)) { -- return ctx.stylize(Date.prototype.toString.call(value), 'date'); -- } -- if (isError(value)) { -- return formatError(value); -- } -- } -- -- var base = '', array = false, braces = ['{', '}']; -- -- // Make Array say that they are Array -- if (isArray(value)) { -- array = true; -- braces = ['[', ']']; -- } -- -- // Make functions say that they are functions -- if (isFunction(value)) { -- var n = value.name ? ': ' + value.name : ''; -- base = ' [Function' + n + ']'; -- } -- -- // Make RegExps say that they are RegExps -- if (isRegExp(value)) { -- base = ' ' + RegExp.prototype.toString.call(value); -- } -- -- // Make dates with properties first say the date -- if (isDate(value)) { -- base = ' ' + Date.prototype.toUTCString.call(value); -- } -- -- // Make error with message first say the error -- if (isError(value)) { -- base = ' ' + formatError(value); -- } -- -- if (keys.length === 0 && (!array || value.length == 0)) { -- return braces[0] + base + braces[1]; -- } -- -- if (recurseTimes < 0) { -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } else { -- return ctx.stylize('[Object]', 'special'); -- } -- } -- -- ctx.seen.push(value); -- -- var output; -- if (array) { -- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); -- } else { -- output = keys.map(function(key) { -- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); -- }); -- } -- -- ctx.seen.pop(); -- -- return reduceToSingleString(output, base, braces); --} -- -- --function formatPrimitive(ctx, value) { -- if (isUndefined(value)) -- return ctx.stylize('undefined', 'undefined'); -- if (isString(value)) { -- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') -- .replace(/'/g, "\\'") -- .replace(/\\"/g, '"') + '\''; -- return ctx.stylize(simple, 'string'); -- } -- if (isNumber(value)) { -- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, -- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . -- if (value === 0 && 1 / value < 0) -- return ctx.stylize('-0', 'number'); -- return ctx.stylize('' + value, 'number'); -- } -- if (isBoolean(value)) -- return ctx.stylize('' + value, 'boolean'); -- // For some reason typeof null is "object", so special case here. -- if (isNull(value)) -- return ctx.stylize('null', 'null'); --} -- -- --function formatError(value) { -- return '[' + Error.prototype.toString.call(value) + ']'; --} -- -- --function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { -- var output = []; -- for (var i = 0, l = value.length; i < l; ++i) { -- if (hasOwnProperty(value, String(i))) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- String(i), true)); -- } else { -- output.push(''); -- } -- } -- keys.forEach(function(key) { -- if (!key.match(/^\d+$/)) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- key, true)); -- } -- }); -- return output; --} -- -- --function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { -- var name, str, desc; -- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; -- if (desc.get) { -- if (desc.set) { -- str = ctx.stylize('[Getter/Setter]', 'special'); -- } else { -- str = ctx.stylize('[Getter]', 'special'); -- } -- } else { -- if (desc.set) { -- str = ctx.stylize('[Setter]', 'special'); -- } -- } -- if (!hasOwnProperty(visibleKeys, key)) { -- name = '[' + key + ']'; -- } -- if (!str) { -- if (ctx.seen.indexOf(desc.value) < 0) { -- if (isNull(recurseTimes)) { -- str = formatValue(ctx, desc.value, null); -- } else { -- str = formatValue(ctx, desc.value, recurseTimes - 1); -- } -- if (str.indexOf('\n') > -1) { -- if (array) { -- str = str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n').substr(2); -- } else { -- str = '\n' + str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n'); -- } -- } -- } else { -- str = ctx.stylize('[Circular]', 'special'); -- } -- } -- if (isUndefined(name)) { -- if (array && key.match(/^\d+$/)) { -- return str; -- } -- name = JSON.stringify('' + key); -- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { -- name = name.substr(1, name.length - 2); -- name = ctx.stylize(name, 'name'); -- } else { -- name = name.replace(/'/g, "\\'") -- .replace(/\\"/g, '"') -- .replace(/(^"|"$)/g, "'"); -- name = ctx.stylize(name, 'string'); -- } -- } -- -- return name + ': ' + str; --} -- -- --function reduceToSingleString(output, base, braces) { -- var numLinesEst = 0; -- var length = output.reduce(function(prev, cur) { -- numLinesEst++; -- if (cur.indexOf('\n') >= 0) numLinesEst++; -- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; -- }, 0); -- -- if (length > 60) { -- return braces[0] + -- (base === '' ? '' : base + '\n ') + -- ' ' + -- output.join(',\n ') + -- ' ' + -- braces[1]; -- } -- -- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; --} -- -- - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { -@@ -522,166 +98,10 @@ function isPrimitive(arg) { - exports.isPrimitive = isPrimitive; - - function isBuffer(arg) { -- return arg instanceof Buffer; -+ return Buffer.isBuffer(arg); - } - exports.isBuffer = isBuffer; - - function objectToString(o) { - return Object.prototype.toString.call(o); --} -- -- --function pad(n) { -- return n < 10 ? '0' + n.toString(10) : n.toString(10); --} -- -- --var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', -- 'Oct', 'Nov', 'Dec']; -- --// 26 Feb 16:19:34 --function timestamp() { -- var d = new Date(); -- var time = [pad(d.getHours()), -- pad(d.getMinutes()), -- pad(d.getSeconds())].join(':'); -- return [d.getDate(), months[d.getMonth()], time].join(' '); --} -- -- --// log is just a thin wrapper to console.log that prepends a timestamp --exports.log = function() { -- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); --}; -- -- --/** -- * Inherit the prototype methods from one constructor into another. -- * -- * The Function.prototype.inherits from lang.js rewritten as a standalone -- * function (not on Function.prototype). NOTE: If this file is to be loaded -- * during bootstrapping this function needs to be rewritten using some native -- * functions as prototype setup using normal JavaScript does not work as -- * expected during bootstrapping (see mirror.js in r114903). -- * -- * @param {function} ctor Constructor function which needs to inherit the -- * prototype. -- * @param {function} superCtor Constructor function to inherit prototype from. -- */ --exports.inherits = function(ctor, superCtor) { -- ctor.super_ = superCtor; -- ctor.prototype = Object.create(superCtor.prototype, { -- constructor: { -- value: ctor, -- enumerable: false, -- writable: true, -- configurable: true -- } -- }); --}; -- --exports._extend = function(origin, add) { -- // Don't do anything if add isn't an object -- if (!add || !isObject(add)) return origin; -- -- var keys = Object.keys(add); -- var i = keys.length; -- while (i--) { -- origin[keys[i]] = add[keys[i]]; -- } -- return origin; --}; -- --function hasOwnProperty(obj, prop) { -- return Object.prototype.hasOwnProperty.call(obj, prop); --} -- -- --// Deprecated old stuff. -- --exports.p = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- console.error(exports.inspect(arguments[i])); -- } --}, 'util.p: Use console.error() instead'); -- -- --exports.exec = exports.deprecate(function() { -- return require('child_process').exec.apply(this, arguments); --}, 'util.exec is now called `child_process.exec`.'); -- -- --exports.print = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(String(arguments[i])); -- } --}, 'util.print: Use console.log instead'); -- -- --exports.puts = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(arguments[i] + '\n'); -- } --}, 'util.puts: Use console.log instead'); -- -- --exports.debug = exports.deprecate(function(x) { -- process.stderr.write('DEBUG: ' + x + '\n'); --}, 'util.debug: Use console.error instead'); -- -- --exports.error = exports.deprecate(function(x) { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stderr.write(arguments[i] + '\n'); -- } --}, 'util.error: Use console.error instead'); -- -- --exports.pump = exports.deprecate(function(readStream, writeStream, callback) { -- var callbackCalled = false; -- -- function call(a, b, c) { -- if (callback && !callbackCalled) { -- callback(a, b, c); -- callbackCalled = true; -- } -- } -- -- readStream.addListener('data', function(chunk) { -- if (writeStream.write(chunk) === false) readStream.pause(); -- }); -- -- writeStream.addListener('drain', function() { -- readStream.resume(); -- }); -- -- readStream.addListener('end', function() { -- writeStream.end(); -- }); -- -- readStream.addListener('close', function() { -- call(); -- }); -- -- readStream.addListener('error', function(err) { -- writeStream.end(); -- call(err); -- }); -- -- writeStream.addListener('error', function(err) { -- readStream.destroy(); -- call(err); -- }); --}, 'util.pump(): Use readableStream.pipe() instead'); -- -- --var uv; --exports._errnoException = function(err, syscall) { -- if (isUndefined(uv)) uv = process.binding('uv'); -- var errname = uv.errname(err); -- var e = new Error(syscall + ' ' + errname); -- e.code = errname; -- e.errno = errname; -- e.syscall = syscall; -- return e; --}; -+} \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js deleted file mode 100755 index 9074e8eb..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -function isBuffer(arg) { - return Buffer.isBuffer(arg); -} -exports.isBuffer = isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json deleted file mode 100755 index 390312c3..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "core-util-is", - "version": "1.0.1", - "description": "The `util.is*` functions introduced in Node v0.12.", - "main": "lib/util.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/core-util-is" - }, - "keywords": [ - "util", - "isBuffer", - "isArray", - "isNumber", - "isString", - "isRegExp", - "isThis", - "isThat", - "polyfill" - ], - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "MIT", - "bugs": { - "url": "https://github.com/isaacs/core-util-is/issues" - }, - "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", - "readmeFilename": "README.md", - "homepage": "https://github.com/isaacs/core-util-is", - "_id": "core-util-is@1.0.1", - "_shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", - "_from": "core-util-is@~1.0.0", - "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz", - "scripts": {} -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js deleted file mode 100755 index 007fa105..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && objectToString(e) === '[object Error]'; -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -function isBuffer(arg) { - return arg instanceof Buffer; -} -exports.isBuffer = isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE deleted file mode 100755 index dea3013d..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. - diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md deleted file mode 100755 index b1c56658..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md +++ /dev/null @@ -1,42 +0,0 @@ -Browser-friendly inheritance fully compatible with standard node.js -[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). - -This package exports standard `inherits` from node.js `util` module in -node environment, but also provides alternative browser-friendly -implementation through [browser -field](https://gist.github.com/shtylman/4339901). Alternative -implementation is a literal copy of standard one located in standalone -module to avoid requiring of `util`. It also has a shim for old -browsers with no `Object.create` support. - -While keeping you sure you are using standard `inherits` -implementation in node.js environment, it allows bundlers such as -[browserify](https://github.com/substack/node-browserify) to not -include full `util` package to your client code if all you need is -just `inherits` function. It worth, because browser shim for `util` -package is large and `inherits` is often the single function you need -from it. - -It's recommended to use this package instead of -`require('util').inherits` for any code that has chances to be used -not only in node.js but in browser too. - -## usage - -```js -var inherits = require('inherits'); -// then use exactly as the standard one -``` - -## note on version ~1.0 - -Version ~1.0 had completely different motivation and is not compatible -neither with 2.0 nor with standard node.js `inherits`. - -If you are using version ~1.0 and planning to switch to ~2.0, be -careful: - -* new version uses `super_` instead of `super` for referencing - superclass -* new version overwrites current prototype while old one preserves any - existing fields on it diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js deleted file mode 100755 index 29f5e24f..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('util').inherits diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js deleted file mode 100755 index c1e78a75..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js +++ /dev/null @@ -1,23 +0,0 @@ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json deleted file mode 100755 index e685e9fb..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "inherits", - "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", - "version": "2.0.1", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented", - "inherits", - "browser", - "browserify" - ], - "main": "./inherits.js", - "browser": "./inherits_browser.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/inherits" - }, - "license": "ISC", - "scripts": { - "test": "node test" - }, - "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/inherits/issues" - }, - "homepage": "https://github.com/isaacs/inherits", - "_id": "inherits@2.0.1", - "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", - "_from": "inherits@~2.0.1", - "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js deleted file mode 100755 index fc53012d..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js +++ /dev/null @@ -1,25 +0,0 @@ -var inherits = require('./inherits.js') -var assert = require('assert') - -function test(c) { - assert(c.constructor === Child) - assert(c.constructor.super_ === Parent) - assert(Object.getPrototypeOf(c) === Child.prototype) - assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) - assert(c instanceof Child) - assert(c instanceof Parent) -} - -function Child() { - Parent.call(this) - test(this) -} - -function Parent() {} - -inherits(Child, Parent) - -var c = new Child -test(c) - -console.log('ok') diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md deleted file mode 100755 index 052a62b8..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md +++ /dev/null @@ -1,54 +0,0 @@ - -# isarray - -`Array#isArray` for older browsers. - -## Usage - -```js -var isArray = require('isarray'); - -console.log(isArray([])); // => true -console.log(isArray({})); // => false -``` - -## Installation - -With [npm](http://npmjs.org) do - -```bash -$ npm install isarray -``` - -Then bundle for the browser with -[browserify](https://github.com/substack/browserify). - -With [component](http://component.io) do - -```bash -$ component install juliangruber/isarray -``` - -## License - -(MIT) - -Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js deleted file mode 100755 index ec58596a..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js +++ /dev/null @@ -1,209 +0,0 @@ - -/** - * Require the given path. - * - * @param {String} path - * @return {Object} exports - * @api public - */ - -function require(path, parent, orig) { - var resolved = require.resolve(path); - - // lookup failed - if (null == resolved) { - orig = orig || path; - parent = parent || 'root'; - var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); - err.path = orig; - err.parent = parent; - err.require = true; - throw err; - } - - var module = require.modules[resolved]; - - // perform real require() - // by invoking the module's - // registered function - if (!module.exports) { - module.exports = {}; - module.client = module.component = true; - module.call(this, module.exports, require.relative(resolved), module); - } - - return module.exports; -} - -/** - * Registered modules. - */ - -require.modules = {}; - -/** - * Registered aliases. - */ - -require.aliases = {}; - -/** - * Resolve `path`. - * - * Lookup: - * - * - PATH/index.js - * - PATH.js - * - PATH - * - * @param {String} path - * @return {String} path or null - * @api private - */ - -require.resolve = function(path) { - if (path.charAt(0) === '/') path = path.slice(1); - var index = path + '/index.js'; - - var paths = [ - path, - path + '.js', - path + '.json', - path + '/index.js', - path + '/index.json' - ]; - - for (var i = 0; i < paths.length; i++) { - var path = paths[i]; - if (require.modules.hasOwnProperty(path)) return path; - } - - if (require.aliases.hasOwnProperty(index)) { - return require.aliases[index]; - } -}; - -/** - * Normalize `path` relative to the current path. - * - * @param {String} curr - * @param {String} path - * @return {String} - * @api private - */ - -require.normalize = function(curr, path) { - var segs = []; - - if ('.' != path.charAt(0)) return path; - - curr = curr.split('/'); - path = path.split('/'); - - for (var i = 0; i < path.length; ++i) { - if ('..' == path[i]) { - curr.pop(); - } else if ('.' != path[i] && '' != path[i]) { - segs.push(path[i]); - } - } - - return curr.concat(segs).join('/'); -}; - -/** - * Register module at `path` with callback `definition`. - * - * @param {String} path - * @param {Function} definition - * @api private - */ - -require.register = function(path, definition) { - require.modules[path] = definition; -}; - -/** - * Alias a module definition. - * - * @param {String} from - * @param {String} to - * @api private - */ - -require.alias = function(from, to) { - if (!require.modules.hasOwnProperty(from)) { - throw new Error('Failed to alias "' + from + '", it does not exist'); - } - require.aliases[to] = from; -}; - -/** - * Return a require function relative to the `parent` path. - * - * @param {String} parent - * @return {Function} - * @api private - */ - -require.relative = function(parent) { - var p = require.normalize(parent, '..'); - - /** - * lastIndexOf helper. - */ - - function lastIndexOf(arr, obj) { - var i = arr.length; - while (i--) { - if (arr[i] === obj) return i; - } - return -1; - } - - /** - * The relative require() itself. - */ - - function localRequire(path) { - var resolved = localRequire.resolve(path); - return require(resolved, parent, path); - } - - /** - * Resolve relative to the parent. - */ - - localRequire.resolve = function(path) { - var c = path.charAt(0); - if ('/' == c) return path.slice(1); - if ('.' == c) return require.normalize(p, path); - - // resolve deps by returning - // the dep in the nearest "deps" - // directory - var segs = parent.split('/'); - var i = lastIndexOf(segs, 'deps') + 1; - if (!i) i = 0; - path = segs.slice(0, i + 1).join('/') + '/deps/' + path; - return path; - }; - - /** - * Check if module is defined at `path`. - */ - - localRequire.exists = function(path) { - return require.modules.hasOwnProperty(localRequire.resolve(path)); - }; - - return localRequire; -}; -require.register("isarray/index.js", function(exports, require, module){ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; - -}); -require.alias("isarray/index.js", "isarray/index.js"); - diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json deleted file mode 100755 index 9e31b683..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name" : "isarray", - "description" : "Array#isArray for older browsers", - "version" : "0.0.1", - "repository" : "juliangruber/isarray", - "homepage": "https://github.com/juliangruber/isarray", - "main" : "index.js", - "scripts" : [ - "index.js" - ], - "dependencies" : {}, - "keywords": ["browser","isarray","array"], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "license": "MIT" -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js deleted file mode 100755 index 5f5ad45d..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json deleted file mode 100755 index 19228ab6..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "isarray", - "description": "Array#isArray for older browsers", - "version": "0.0.1", - "repository": { - "type": "git", - "url": "git://github.com/juliangruber/isarray.git" - }, - "homepage": "https://github.com/juliangruber/isarray", - "main": "index.js", - "scripts": { - "test": "tap test/*.js" - }, - "dependencies": {}, - "devDependencies": { - "tap": "*" - }, - "keywords": [ - "browser", - "isarray", - "array" - ], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "license": "MIT", - "_id": "isarray@0.0.1", - "dist": { - "shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", - "tarball": "http://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz" - }, - "_from": "isarray@0.0.1", - "_npmVersion": "1.2.18", - "_npmUser": { - "name": "juliangruber", - "email": "julian@juliangruber.com" - }, - "maintainers": [ - { - "name": "juliangruber", - "email": "julian@juliangruber.com" - } - ], - "directories": {}, - "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", - "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "bugs": { - "url": "https://github.com/juliangruber/isarray/issues" - }, - "readme": "ERROR: No README data found!" -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore deleted file mode 100755 index 206320cc..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -build -test diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE deleted file mode 100755 index 6de584a4..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, subject to the -following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md deleted file mode 100755 index 4d2aa001..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md +++ /dev/null @@ -1,7 +0,0 @@ -**string_decoder.js** (`require('string_decoder')`) from Node.js core - -Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. - -Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** - -The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js deleted file mode 100755 index b00e54fb..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -var Buffer = require('buffer').Buffer; - -var isBufferEncoding = Buffer.isEncoding - || function(encoding) { - switch (encoding && encoding.toLowerCase()) { - case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; - default: return false; - } - } - - -function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. CESU-8 is handled as part of the UTF-8 encoding. -// -// @TODO Handling all encodings inside a single object makes it very difficult -// to reason about this code, so it should be split up in the future. -// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code -// points as used by CESU-8. -var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } - - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; -}; - - -// write decodes the given buffer and returns it as JS string that is -// guaranteed to not contain any partial multi-byte characters. Any partial -// character found at the end of the buffer is buffered up, and will be -// returned when calling write again with the remaining bytes. -// -// Note: Converting a Buffer containing an orphan surrogate to a String -// currently works, but converting a String to a Buffer (via `new Buffer`, or -// Buffer#write) will replace incomplete surrogates with the unicode -// replacement character. See https://codereview.chromium.org/121173009/ . -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } - - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } - - charStr += buffer.toString(this.encoding, 0, end); - - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } - - // or just emit the charStr - return charStr; -}; - -// detectIncompleteChar determines if there is an incomplete UTF-8 character at -// the end of the given buffer. If so, it sets this.charLength to the byte -// length that character, and sets this.charReceived to the number of bytes -// that are available for this character. -StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; -}; - -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; -}; - -function passThroughWrite(buffer) { - return buffer.toString(this.encoding); -} - -function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; -} - -function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json deleted file mode 100755 index 1adbbb61..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "string_decoder", - "version": "0.10.31", - "description": "The string_decoder module from Node core", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "tap": "~0.4.8" - }, - "scripts": { - "test": "tap test/simple/*.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/rvagg/string_decoder.git" - }, - "homepage": "https://github.com/rvagg/string_decoder", - "keywords": [ - "string", - "decoder", - "browser", - "browserify" - ], - "license": "MIT", - "readme": "**string_decoder.js** (`require('string_decoder')`) from Node.js core\n\nCopyright Joyent, Inc. and other Node contributors. See LICENCE file for details.\n\nVersion numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.**\n\nThe *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version.", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/rvagg/string_decoder/issues" - }, - "_id": "string_decoder@0.10.31", - "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", - "_from": "string_decoder@~0.10.x", - "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz" -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/package.json b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/package.json deleted file mode 100755 index 153fb546..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "name": "readable-stream", - "version": "1.0.33", - "description": "Streams2, a user-land copy of the stream library from Node.js v0.10.x", - "main": "readable.js", - "dependencies": { - "core-util-is": "~1.0.0", - "isarray": "0.0.1", - "string_decoder": "~0.10.x", - "inherits": "~2.0.1" - }, - "devDependencies": { - "tap": "~0.2.6" - }, - "scripts": { - "test": "tap test/simple/*.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/isaacs/readable-stream" - }, - "keywords": [ - "readable", - "stream", - "pipe" - ], - "browser": { - "util": false - }, - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "MIT", - "gitHead": "0bf97a117c5646556548966409ebc57a6dda2638", - "bugs": { - "url": "https://github.com/isaacs/readable-stream/issues" - }, - "homepage": "https://github.com/isaacs/readable-stream", - "_id": "readable-stream@1.0.33", - "_shasum": "3a360dd66c1b1d7fd4705389860eda1d0f61126c", - "_from": "readable-stream@latest", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "rvagg", - "email": "rod@vagg.org" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - }, - { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - }, - { - "name": "rvagg", - "email": "rod@vagg.org" - } - ], - "dist": { - "shasum": "3a360dd66c1b1d7fd4705389860eda1d0f61126c", - "tarball": "http://registry.npmjs.org/readable-stream/-/readable-stream-1.0.33.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.33.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/passthrough.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/passthrough.js deleted file mode 100755 index 27e8d8a5..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/passthrough.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_passthrough.js") diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/readable.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/readable.js deleted file mode 100755 index 8b5337b5..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/readable.js +++ /dev/null @@ -1,8 +0,0 @@ -var Stream = require('stream'); // hack to fix a circular dependency issue when used with browserify -exports = module.exports = require('./lib/_stream_readable.js'); -exports.Stream = Stream; -exports.Readable = exports; -exports.Writable = require('./lib/_stream_writable.js'); -exports.Duplex = require('./lib/_stream_duplex.js'); -exports.Transform = require('./lib/_stream_transform.js'); -exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/transform.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/transform.js deleted file mode 100755 index 5d482f07..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/transform.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_transform.js") diff --git a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/writable.js b/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/writable.js deleted file mode 100755 index e1e9efdf..00000000 --- a/server/node_modules/monk/node_modules/mongodb/node_modules/readable-stream/writable.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_writable.js") diff --git a/server/node_modules/monk/node_modules/mongodb/package.json b/server/node_modules/monk/node_modules/mongodb/package.json deleted file mode 100755 index 6971e551..00000000 --- a/server/node_modules/monk/node_modules/mongodb/package.json +++ /dev/null @@ -1,252 +0,0 @@ -{ - "name": "mongodb", - "description": "A node.js driver for MongoDB", - "keywords": [ - "mongodb", - "mongo", - "driver", - "db" - ], - "version": "1.4.35", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "contributors": [ - { - "name": "Aaron Heckmann" - }, - { - "name": "Christoph Pojer" - }, - { - "name": "Pau Ramon Revilla" - }, - { - "name": "Nathan White" - }, - { - "name": "Emmerman" - }, - { - "name": "Seth LaForge" - }, - { - "name": "Boris Filipov" - }, - { - "name": "Stefan Schärmeli" - }, - { - "name": "Tedde Lundgren" - }, - { - "name": "renctan" - }, - { - "name": "Sergey Ukustov" - }, - { - "name": "Ciaran Jessup" - }, - { - "name": "kuno" - }, - { - "name": "srimonti" - }, - { - "name": "Erik Abele" - }, - { - "name": "Pratik Daga" - }, - { - "name": "Slobodan Utvic" - }, - { - "name": "Kristina Chodorow" - }, - { - "name": "Yonathan Randolph" - }, - { - "name": "Brian Noguchi" - }, - { - "name": "Sam Epstein" - }, - { - "name": "James Harrison Fisher" - }, - { - "name": "Vladimir Dronnikov" - }, - { - "name": "Ben Hockey" - }, - { - "name": "Henrik Johansson" - }, - { - "name": "Simon Weare" - }, - { - "name": "Alex Gorbatchev" - }, - { - "name": "Shimon Doodkin" - }, - { - "name": "Kyle Mueller" - }, - { - "name": "Eran Hammer-Lahav" - }, - { - "name": "Marcin Ciszak" - }, - { - "name": "François de Metz" - }, - { - "name": "Vinay Pulim" - }, - { - "name": "nstielau" - }, - { - "name": "Adam Wiggins" - }, - { - "name": "entrinzikyl" - }, - { - "name": "Jeremy Selier" - }, - { - "name": "Ian Millington" - }, - { - "name": "Public Keating" - }, - { - "name": "andrewjstone" - }, - { - "name": "Christopher Stott" - }, - { - "name": "Corey Jewett" - }, - { - "name": "brettkiefer" - }, - { - "name": "Rob Holland" - }, - { - "name": "Senmiao Liu" - }, - { - "name": "heroic" - }, - { - "name": "gitfy" - }, - { - "name": "Andrew Stone" - }, - { - "name": "John Le Drew" - }, - { - "name": "Lucasfilm Singapore" - }, - { - "name": "Roman Shtylman" - }, - { - "name": "Matt Self" - }, - { - "name": "Gregory Langlais" - }, - { - "name": "Samantha Ritter" - } - ], - "repository": { - "type": "git", - "url": "http://github.com/mongodb/node-mongodb-native.git" - }, - "bugs": { - "url": "http://github.com/mongodb/node-mongodb-native/issues" - }, - "dependencies": { - "bson": "~0.2", - "kerberos": "0.0.9", - "readable-stream": "latest" - }, - "devDependencies": { - "dox": "0.4.4", - "uglify-js": "1.2.5", - "ejs": "0.6.1", - "request": "2.12.0", - "nodeunit": "0.7.3", - "markdown": "0.3.1", - "gleak": "0.5.0", - "step": "0.0.5", - "async": "0.1.22", - "integra": "0.1.8", - "optimist": "latest", - "rimraf": "2.2.6", - "semver": "4.1.0", - "mongodb-version-manager": "0.5.0", - "mongodb-tools": "~1.0" - }, - "optionalDependencies": { - "kerberos": "0.0.9", - "readable-stream": "latest" - }, - "config": { - "native": false - }, - "main": "./lib/mongodb/index", - "homepage": "http://mongodb.github.com/node-mongodb-native/", - "directories": { - "lib": "./lib/mongodb" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "test": "node test/runner.js -t functional" - }, - "licenses": [ - { - "type": "Apache License, Version 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0" - } - ], - "gitHead": "02bf8ece1227b0c35448fe16f5d0073de26106a7", - "_id": "mongodb@1.4.35", - "_shasum": "b5d57ee071d058f385db68e85bedb526c1caba43", - "_from": "mongodb@~1.4", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "maintainers": [ - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "b5d57ee071d058f385db68e85bedb526c1caba43", - "tarball": "http://registry.npmjs.org/mongodb/-/mongodb-1.4.35.tgz" - }, - "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-1.4.35.tgz" -} diff --git a/server/node_modules/monk/node_modules/mongodb/wercker.yml b/server/node_modules/monk/node_modules/mongodb/wercker.yml deleted file mode 100755 index db008aef..00000000 --- a/server/node_modules/monk/node_modules/mongodb/wercker.yml +++ /dev/null @@ -1,17 +0,0 @@ -box: wercker/nodejs -# Build definition -build: - # The steps that will be executed on build - steps: - # A step that executes `npm install` command - - npm-install - # A step that executes `npm test` command - - npm-test - - # A custom script step, name value is used in the UI - # and the code value contains the command that get executed - - script: - name: echo nodejs information - code: | - echo "node version $(node -v) running" - echo "npm version $(npm -v) running" diff --git a/server/node_modules/monk/node_modules/mongoskin/.jshintrc b/server/node_modules/monk/node_modules/mongoskin/.jshintrc deleted file mode 100755 index bbe0a3e8..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/.jshintrc +++ /dev/null @@ -1,43 +0,0 @@ -{ - "predef": [ - "phantom", - "module", - "require", - "__dirname", - "process", - "console", - "it", - "describe", - "before", - "beforeEach", - "after", - "should", - "rewire", - "$" - ], - - "browser": true, - "node" : true, - "es5": true, - "bitwise": true, - "curly": true, - "eqeqeq": true, - "forin": false, - "immed": true, - "latedef": true, - "newcap": true, - "noarg": true, - "noempty": true, - "nonew": true, - "plusplus": false, - "undef": true, - "strict": true, - "trailing": false, - "globalstrict": true, - "nonstandard": true, - "white": false, - "indent": 2, - "expr": true, - "multistr": true, - "onevar": false -} \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongoskin/.npmignore b/server/node_modules/monk/node_modules/mongoskin/.npmignore deleted file mode 100755 index cbd931a5..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/.npmignore +++ /dev/null @@ -1,6 +0,0 @@ -data/ -deps/ -coverage.html -lib-cov -test/ -test_results.md diff --git a/server/node_modules/monk/node_modules/mongoskin/.travis.yml b/server/node_modules/monk/node_modules/mongoskin/.travis.yml deleted file mode 100755 index cc7113e6..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: node_js -node_js: - - 0.8 - - 0.10 - - 0.11 -script: make coveralls -services: - - mongodb diff --git a/server/node_modules/monk/node_modules/mongoskin/AUTHORS b/server/node_modules/monk/node_modules/mongoskin/AUTHORS deleted file mode 100755 index 99e04c19..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/AUTHORS +++ /dev/null @@ -1,16 +0,0 @@ -# Total 12 contributors. -# Ordered by date of first contribution. -# Auto-generated (http://github.com/dtrejo/node-authors) on Tue Aug 14 2012 02:58:57 GMT+0800 (CST). - -Gui Lin (https://github.com/guileen) -François de Metz (https://github.com/francois2metz) -fengmk2 (http://fengmk2.github.com) -Quang Van (https://github.com/quangv) -Matt Perpick (https://github.com/clutchski) -humanchimp (https://github.com/humanchimp) -Joe Faber (https://github.com/jlfaber) -Harvey McQueen (https://github.com/hmcqueen) -Paul Gebheim (https://github.com/paulirish) -Aneil Mallavarapu (https://github.com/amallavarapu) -wmertens (https://github.com/wmertens) -Rakshit Menpara (https://github.com/deltasquare4) diff --git a/server/node_modules/monk/node_modules/mongoskin/History.md b/server/node_modules/monk/node_modules/mongoskin/History.md deleted file mode 100755 index 1fecf663..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/History.md +++ /dev/null @@ -1,82 +0,0 @@ - -0.6.1 / 2013-11-24 -================== - - * Merge pull request #122 from Philmod/older-mongodb - * older version of mongodb - * Merge pull request #108 from fresheneesz/patch-1 - * Merge pull request #114 from nemtsov/patch-1 - * fix typo: this.hit -> this.hint - * Vastly improving the documentation around the mongoskin.db method - -0.6.0 / 2013-07-16 -================== - - * changed version in package.json to 1.3.x for mongodb - * Upgraded the mongo db version to 1.3.x. Mixing mongodb 1.2.x which mongoskin 0.5.0 depends on and latest mongodb 1.3.x causes Mongodb connection timeout problems in replication environment. - * Use HTTPS so GitHub doesn't cache dependency badge - * add Dependencies status image - * Corrected repository URL in package.json - * Documentation improvements - * add 0.9 version test - -0.5.0 / 2012-12-29 -================== - - * fixed unsafe mode warnning log - * Merge pull request #84 from kingpearl/master - * MongoDB 1.2.x support - * Merge pull request #73 from jockster/master - * Merge pull request #75 from voke/patch-1 - * Fix typo - * fixed bind() test cases; - * Minor error in readme. Now updated - * Updated readme according to issue #72 - -0.3.4 / 2011-03-24 - * fix global leaks - -0.3.3 / 2011-03-15 -================== - * Add rootCollection option to SkinGridStore.exist - -0.3.2 / 2011-03-01 -================== - * exports all classes of node-mongodb-native - -0.3.1 / 2011-02-26 -================== - * bug fix #33 - -0.3.0 / 2011-01-19 -================== - * add ReplSet support - * bug fix - -0.2.3 / 2011-01-03 -================== - * add db.toObjectID - * fix #25 for node-mongodb-native update - -0.2.2 / 2011-12-02 -================== - * add bind support for embeded collections, e.g. db.bind('system.js') - * add method `toId` to SkinDB - * add property `ObjectID`, `bson_serializer` to SkinDB. - * SkinCollection.prototype.id is now deprecated. - -0.2.1 / 2011-11-18 -================== - * add ObjectId support for XXXXById - -0.2.0 / 2011-11-06 -================== - * add SkinDB.gridfs - -0.1.3 / 2011-05-24 -================== - * add SkinCollection.removeById - -0.1.2 / 2011-04-30 -================== - * add mongoskin.router diff --git a/server/node_modules/monk/node_modules/mongoskin/LICENSE b/server/node_modules/monk/node_modules/mongoskin/LICENSE deleted file mode 100755 index e91ac035..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2011 - 2012 kissjs.org - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongoskin/Makefile b/server/node_modules/monk/node_modules/mongoskin/Makefile deleted file mode 100755 index 98488b0f..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -MONGOSKIN_REPLICASET = false -NODE_BIN=./node_modules/.bin -MOCHA=$(NODE_BIN)/mocha -COVERALLS=$(NODE_BIN)/coveralls - -test: - @$(MOCHA) -R spec - -test-debug: - @$(MOCHA) -R spec debug - -test-replicaset: - @MONGOSKIN_REPLICASET=true $(MOCHA) - -test-cov: - @$(MOCHA) -R html-cov > coverage.html - -coveralls: - @$(MOCHA) -R mocha-lcov-reporter | $(COVERALLS) - -test-watch: - @$(MOCHA) -w -R dot --growl - -.PHONY: test-cov test-replicaset test test-debug diff --git a/server/node_modules/monk/node_modules/mongoskin/Readme.md b/server/node_modules/monk/node_modules/mongoskin/Readme.md deleted file mode 100755 index 8b6b507e..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/Readme.md +++ /dev/null @@ -1,260 +0,0 @@ -[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/kissjs/node-mongoskin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - -# mongoskin - -[![Build Status](https://secure.travis-ci.org/kissjs/node-mongoskin.png)](http://travis-ci.org/kissjs/node-mongoskin) -[![Dependencies](https://david-dm.org/kissjs/node-mongoskin.png)](https://david-dm.org/kissjs/node-mongoskin) -[![Coverage Status](https://coveralls.io/repos/kissjs/node-mongoskin/badge.png?branch=master)](https://coveralls.io/r/kissjs/node-mongoskin?branch=master) -[![NPM version](https://badge.fury.io/js/mongoskin.png)](http://badge.fury.io/js/mongoskin) - -[![NPM](https://nodei.co/npm/mongoskin.png?downloads=true&stars=true)](https://nodei.co/npm/mongoskin/) - -[![NPM](https://nodei.co/npm-dl/mongoskin.png?months=6)](https://nodei.co/npm/mongoskin/) - -Install -======== - -```bash -$ npm install mongoskin -``` - -Usage -======== - -Use dburl - -```js -var mongo = require('mongoskin'); -var db = mongo.db("mongodb://localhost:27017/integration_tests", {native_parser:true}); -db.bind('article'); -db.article.find().toArray(function(err, items) { - db.close(); -}); -``` - -Use ReplSet - -```js -var mongo = require('mongoskin'); -var Server = mongo.Server; -var Db = mongo.Db; - -var replSet = new ReplSetServers([ - new Server('localhost', 30000), - new Server('localhost', 30001), - new Server('localhost', 30002), -]); - -var db = new Db('integration_test_', replSet, {w:0, native_parser: (process.env['TEST_NATIVE'] != null)}); -// no need open and on('fullsetup', ...) -db.collection('myconnection').find().setReadPreference(ReadPreference.SECONDARY).toArray(function(err, items) { - db.close(); -}); -``` - -Model helper: - -```js -var mongo = require('mongoskin'); -var db = mongo.db("mongodb://localhost:27017/integration_tests", {native_parser:true}); -db.bind('article').bind({ - getByAuthor: function(author_id, callback) { - this.findOne({author_id: author_id}, callback); - } -}); -db.article.getByAuthor(author_id, function(err, article) { - console.log(article); -}); -``` - -## Origin API part -For detail API reference see [node mongodb API](http://mongodb.github.io/node-mongodb-native/). Mongoskin is just change the API call chain. - -We make some common use functions in promise mode, we call it SkinClass of a normal Class. And the API is almost same with official API. - -### module - -origin: -```js -var mongo = require('mongodb'); -var Db = mongo.Db; -var Server = mongo.Server; -var MongoClient = mongo.MongoClient; -var ReplSetServers = mongo.ReplSetServers; -... -``` - -mongoskin: - -```js -var mongo = require('mongoskin'); -var Db = mongo.Db; -var Server = mongo.Server; -var MongoClient = mongo.MongoClient; -var ReplSetServers = mongo.ReplSetServers; -... -``` - -### MongoClient.connect(...) - -returns a `Db` instance - -alias origin `MongoClient.connect(..., function(err, db) { .... })` - -origin: - -```js -MongoClient.connect(..., function(err, db) { -}) -``` - -mongoskin: - -```js -var db = MongoClient.connect(...) -``` - -### db.collection(..., [callback]) - -returns a `Collection` instance - -alias origin `db.collection(..., function(err, collection) {....})` - -origin: - -```js -var db = new Db(...); -db.open(function(err, db) { - db.collection('myCollection', {strict: true}, function(err, myCollection) { - // myCollection.find() ... - }); -}); -``` - -mongoskin: - -```js -var db = new Db(...); -var myCollection = db.collection('myCollection', {strict: true}); -``` - -## MongoSkin API part - -### module.db(...) -alias `MongoClient.connect(...)` -### module.helper.toObjectID(hexStr) -convert `String` to `ObjectID` instance. -### db.bind(name, options) -alias `db[name] = db.collection(name, options)` - -```js -db.bind('article') -db.article.find().toArray(function(err, items) { - assert.ok(err == null); -}); -``` - -### db.admin(...) -alias `new Admin(db, ...)` -### db.grid(...) -alias `new Grid(db, ...)` -### db.gridStore(...) -alias `new GridStore(db, ...)` -### collection.bind(extendObject) -each method of extendObject will be bind to collection. -### collection.findById(id, ...) -alias `collection.find({_id: toObjectID(id)}, ...)` -### collection.updateById(id, ...) -alias `collection.update({_id: toObjectID(id)}, ...)` -### collection.removeById(id, ...) -alias `collection.remove({_id: toObjectID(id)}, ...)` - -## NOTE!! mongoskin API change from 1.3.20 - -Since node-mongodb-native has change a lot of API, mongoskin redesign from 1.3.20. The version number keep same with node-mongodb-native. And the API appearence is also keep same with node-mongodb-native - -### Removed API from mongoskin 1.3.20 - -* module.bind -* module.Skin* -* module.router -* skinDb.toId -* skinDb.toObjectId -* skinDb.gridfs -* skinCollection.bind - -### Modified API from mongoskin 1.3.20 - -* module.db -* skinDb.bind - - -### Additional API from mongoskin 1.3.20 - -* module.MongoClient -* module.Grid -* module.GridStore -* module.helper.toObjectID - -## Authors - -Below is the output from `git-summary`. - -``` - project : node-mongoskin - repo age : 2 years, 10 months - active : 84 days - commits : 180 - files : 44 - authors : - 49 Lin Gui 27.2% - 44 fengmk2 24.4% - 34 guilin 桂林 18.9% - 23 Gui Lin 12.8% - 5 guilin 2.8% - 2 Raghu Katti 1.1% - 2 Merlyn Albery-Speyer 1.1% - 2 Paul Gebheim 1.1% - 2 Joakim B 1.1% - 2 François de Metz 1.1% - 1 Wout Mertens 0.6% - 1 Yuriy Nemtsov 0.6% - 1 fresheneesz 0.6% - 1 humanchimp 0.6% - 1 Alan Shaw 0.6% - 1 wmertens 0.6% - 1 Aneil Mallavarapu 0.6% - 1 Gustav 0.6% - 1 Harvey McQueen 0.6% - 1 Joe Faber 0.6% - 1 Matt Perpick 0.6% - 1 Philmod 0.6% - 1 Quang Van 0.6% - 1 Rakshit Menpara 0.6% - 1 Shawn Jonnet 0.6% -``` - -## License - -(The MIT License) - -Copyright (c) 2011 - 2012 kissjs.org - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/monk/node_modules/mongoskin/examples/admin.js b/server/node_modules/monk/node_modules/mongoskin/examples/admin.js deleted file mode 100755 index c6d0d85f..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/examples/admin.js +++ /dev/null @@ -1,9 +0,0 @@ -var db = require('./config').db; - -db.admin().listDatabases(function(err, result){ - if(err) { - console.traceError(err); - } - console.log(result); - db.close(); -}) diff --git a/server/node_modules/monk/node_modules/mongoskin/examples/close.js b/server/node_modules/monk/node_modules/mongoskin/examples/close.js deleted file mode 100755 index 73fafaa1..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/examples/close.js +++ /dev/null @@ -1,15 +0,0 @@ -var db = require('./config').db; - -db.collection('test').findOne({}, function(err, data) { - if(!err) { - console.log('db has open'); - console.log(data); - } -}); - -process.on('SIGINT', function() { - console.log('Recieve SIGINT'); - db.close(function(){ - console.log('database has closed'); - }) -}) diff --git a/server/node_modules/monk/node_modules/mongoskin/examples/config.js b/server/node_modules/monk/node_modules/mongoskin/examples/config.js deleted file mode 100755 index 9d8e0fb3..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/examples/config.js +++ /dev/null @@ -1,3 +0,0 @@ -var mongo = require('../'); - -exports.db = mongo.db('mongodb://localhost/test'); diff --git a/server/node_modules/monk/node_modules/mongoskin/examples/generateId.js b/server/node_modules/monk/node_modules/mongoskin/examples/generateId.js deleted file mode 100755 index 6acb4bfe..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/examples/generateId.js +++ /dev/null @@ -1,31 +0,0 @@ -var redis = require('redis').createClient() - , shorten = require('shorten')(redis) - , async = require('async') - , db = require('./config').db - ; - -db.bind('user'); - -function log(err) { - if(err) { - console.log(err.stack); - } -} - -function createUser(user, callback) { - - async.waterfall([ - function(fn) { - shorten.nextId('user', fn); - } - , function(uid, fn) { - user.uid = uid; - db.user.save(user, fn); - } - ], callback); - -} - -for(var i = 0; i<10; i++) { - createUser({name: 'user' + i}, log); -} diff --git a/server/node_modules/monk/node_modules/mongoskin/examples/gridfs.js b/server/node_modules/monk/node_modules/mongoskin/examples/gridfs.js deleted file mode 100755 index 2a72c0ff..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/examples/gridfs.js +++ /dev/null @@ -1,11 +0,0 @@ -var db = require('./config').db; - -var gs = db.gridStore('test.txt', 'w') -gs.write('blablabla', function(err, reply) { - gs.close(function(err, reply){ - var gs = db.gridStore('test.txt', 'r') - gs.read(function(err, reply){ - console.log(reply.toString()); - }); - }); -}); diff --git a/server/node_modules/monk/node_modules/mongoskin/examples/insert.js b/server/node_modules/monk/node_modules/mongoskin/examples/insert.js deleted file mode 100755 index bba4c580..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/examples/insert.js +++ /dev/null @@ -1,8 +0,0 @@ -var db = require('./config').db; - -db.collection('test').insert({foo: 'bar'}, function(err, result) { - console.log(result); - db.collection('test').drop(); - db.close(); - -}); diff --git a/server/node_modules/monk/node_modules/mongoskin/examples/replSetBenchmark.js b/server/node_modules/monk/node_modules/mongoskin/examples/replSetBenchmark.js deleted file mode 100755 index bacd59eb..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/examples/replSetBenchmark.js +++ /dev/null @@ -1,45 +0,0 @@ - -var mongo = require('../'); - -var conf = { - hosts: [ - '127.0.0.1:27110/?auto_reconnect', - '127.0.0.1:27111/?auto_reconnect' - ], - dataDB: 'test' -}; - -var db = exports.db = mongo.db(conf.hosts, { - database: conf.dataDB -}); - -var noop = function() {}; - -db.bind('user'); -// db.user.ensureIndex({ name: 1 }, { unique: true }, noop); -// db.user.ensureIndex({ enable: 1 }, noop); -// db.user.ensureIndex({ created_at: 1, enable: 1 }, noop); - -var counter = 0; -setInterval(function () { - db.user.findItems({ name: 'name_' + counter }, function (err, items) { - if (err) { - console.error('findItems user error', err); - } - if (items) { - console.log('total: %d users', items.length); - } - }); - db.user.insert({ - name: 'name_' + counter, - createtime: new Date() - }, function(err, user) { - if (err) { - console.error('insert user error', err); - } - if (user && user[0]) { - console.log('new: %d %s', counter, user[0]._id); - } - }); - counter++; -}, 10); diff --git a/server/node_modules/monk/node_modules/mongoskin/examples/replset.js b/server/node_modules/monk/node_modules/mongoskin/examples/replset.js deleted file mode 100755 index cadb5ea9..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/examples/replset.js +++ /dev/null @@ -1,17 +0,0 @@ -var mongo = require('../'); -var Db = mongo.Db; -var Server = mongo.Server; -var ReplSetServers = mongo.ReplSetServers; - -var replSet = new ReplSetServers([ - new Server('localhost', 30000), - new Server('localhost', 30001), - new Server('localhost', 30002) -]); -var db = new Db('integration_test_', replSet, {w:0}); -db.collection('article').find().toArray(function(err, data) { - console.log(err && err.stack); - console.log(data); - -}); - diff --git a/server/node_modules/monk/node_modules/mongoskin/examples/update.js b/server/node_modules/monk/node_modules/mongoskin/examples/update.js deleted file mode 100755 index 080d84e3..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/examples/update.js +++ /dev/null @@ -1,19 +0,0 @@ -var db = require('./config').db; -var articles = db.collection('articles'); -articles.insert({foo: 'bar', val: 'val1'}, function(err, result) { - - console.log(result); - articles.update({foo:'bar'}, {foo: 'bar', val:'val2'}, {strict: true}, function(err, result) { - - console.log(result); - articles.find({foo: 'bar'}).toArray(function(err, docs){ - - console.log(docs); - articles.drop(); - db.close(); - - }); - - }) - -}); diff --git a/server/node_modules/monk/node_modules/mongoskin/index.js b/server/node_modules/monk/node_modules/mongoskin/index.js deleted file mode 100755 index 93a84762..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = process.env.MONGOSKIN_COV ? require('./lib-cov/') : require('./lib/'); diff --git a/server/node_modules/monk/node_modules/mongoskin/lib/admin.js b/server/node_modules/monk/node_modules/mongoskin/lib/admin.js deleted file mode 100755 index 95575e9d..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/lib/admin.js +++ /dev/null @@ -1,26 +0,0 @@ -/*! - * mongoskin - admin.js - * - * Copyright(c) 2011 - 2012 kissjs.org - * Copyright(c) 2012 fengmk2 - * MIT Licensed - */ - -"use strict"; - -/** - * Module dependencies. - */ - -var Admin = require('mongodb').Admin; -var makeSkinClass = require('./utils').makeSkinClass; - -var SkinAdmin = exports.SkinAdmin = makeSkinClass(Admin, false, true); - -SkinAdmin.prototype._open = function(callback) { - var skindb = this._construct_args[0]; - skindb.open(function(err, p_db) { - if(err) return callback(err); - callback(null, p_db.admin()); - }); -}; diff --git a/server/node_modules/monk/node_modules/mongoskin/lib/collection.js b/server/node_modules/monk/node_modules/mongoskin/lib/collection.js deleted file mode 100755 index 28673903..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/lib/collection.js +++ /dev/null @@ -1,192 +0,0 @@ -/*! - * mongoskin - collection.js - * - * Copyright(c) 2011 - 2012 kissjs.org - * Copyright(c) 2012 fengmk2 - * MIT Licensed - */ - -"use strict"; - -/** - * Module dependencies. - */ -var __slice = Array.prototype.slice; -var Collection = require('mongodb').Collection; -var SkinCursor = require('./cursor').SkinCursor; -var helper = require('./helper'); -var utils = require('./utils'); - -/** - * Constructor - */ -var SkinCollection = exports.SkinCollection = utils.makeSkinClass(Collection); - -/** - * bind extend functions to collection - * - * e.g. - * - * db.bind('article').bind({ - * getPostByAuthor: function(id, callback) { - * this.findOne({author_id: id}, callback); - * } - * }); - * - */ -SkinCollection.prototype.bind = function(extendObject) { - for(var key in extendObject) { - if(typeof extendObject[key] == 'function') { - this[key] = extendObject[key].bind(this); - } else { - this[key] = extendObject[key]; - } - } -} - -SkinCollection.prototype._open = function(callback) { - var collection_args = this._collection_args.concat([callback]); - this._skin_db.open(function(err, db) { - if(err) return callback(err); - db.collection.apply(db, collection_args); - }); -} - -/* - * find is a special method, because it could return a SkinCursor instance - */ -SkinCollection.prototype._find = SkinCollection.prototype.find; - -/** - * same args as find, but use Array as callback result but not use Cursor - * - * findItems(args, function (err, items) {}); - * - * same as - * - * find(args).toArray(function (err, items) {}); - * - * or using `mongodb.collection.find()` - * - * find(args, function (err, cursor) { - * cursor.toArray(function (err, items) { - * }); - * }); - * - * @param {Object} [query] - * @param {Object} [options] - * @param {Function(err, docs)} callback - * @return {SkinCollection} this - * @api public - */ -SkinCollection.prototype.findItems = function (query, options, callback) { - var args = __slice.call(arguments); - var fn = args[args.length - 1]; - args[args.length - 1] = function (err, cursor) { - if (err) { - return fn(err); - } - cursor.toArray(fn); - }; - this.find.apply(this, args); - return this; -}; - -/** - * find and cursor.each(fn). - * - * @param {Object} [query] - * @param {Object} [options] - * @param {Function(err, item)} eachCallback - * @return {SkinCollection} this - * @api public - */ -SkinCollection.prototype.findEach = function (query, options, eachCallback) { - var args = __slice.call(arguments); - var fn = args[args.length - 1]; - args[args.length - 1] = function (err, cursor) { - if (err) { - return fn(err); - } - cursor.each(fn); - }; - this.find.apply(this, args); - return this; -}; - -/** - * Operate by object.`_id` - * - * @param {String} methodName - * @param {String|ObjectID|Number} id - * @param {Arguments|Array} args - * @return {SkinCollection} this - * @api private - */ -SkinCollection.prototype._operateById = function (methodName, id, args) { - args = __slice.call(args); - args[0] = {_id: helper.toObjectID(id)}; - this[methodName].apply(this, args); - return this; -}; - -/** - * Find one object by _id. - * - * @param {String|ObjectID|Number} id, doc primary key `_id` - * @param {Function(err, doc)} callback - * @return {SkinCollection} this - * @api public - */ -SkinCollection.prototype.findById = function (id, callback) { - return this._operateById('findOne', id, arguments); -}; - -/** - * Update doc by _id. - * @param {String|ObjectID|Number} id, doc primary key `_id` - * @param {Object} doc - * @param {Function(err)} callback - * @return {SkinCollection} this - * @api public - */ -SkinCollection.prototype.updateById = function (id, doc, callback) { - return this._operateById('update', id, arguments); -}; - -/** - * Remove doc by _id. - * @param {String|ObjectID|Number} id, doc primary key `_id` - * @param {Function(err)} callback - * @return {SkinCollection} this - * @api public - */ -SkinCollection.prototype.removeById = function (id, callback) { - return this._operateById('remove', id, arguments); -}; - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB. - * - * @param {Object} query - * @param {Object} options - * @param {Function(err, docs)} callback - * @return {SkinCursor|SkinCollection} if last argument is not a function, then returns a SkinCursor, - * otherise return this - * @api public - */ -SkinCollection.prototype.find = function (query, options, callback) { - var args = __slice.call(arguments); - if(this.isOpen()) { - return this._native.find.apply(this._native, args); - } - if (args.length > 0 && typeof args[args.length - 1] === 'function') { - this._find.apply(this, args); - return this; - } else { - var cursor = new SkinCursor(); - cursor._skin_collection = this; - cursor._find_args = args; - return cursor; - } -}; diff --git a/server/node_modules/monk/node_modules/mongoskin/lib/constant.js b/server/node_modules/monk/node_modules/mongoskin/lib/constant.js deleted file mode 100755 index b9fb9070..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/lib/constant.js +++ /dev/null @@ -1,15 +0,0 @@ -/*! - * mongoskin - constant.js - * - * Copyright(c) 2011 - 2012 kissjs.org - * Copyright(c) 2012 fengmk2 - * MIT Licensed - */ - -"use strict"; - -exports.DEFAULT_PORT = 27017; - -exports.STATE_CLOSE = 0; -exports.STATE_OPENNING = 1; -exports.STATE_OPEN = 2; \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mongoskin/lib/cursor.js b/server/node_modules/monk/node_modules/mongoskin/lib/cursor.js deleted file mode 100755 index 2a4d062e..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/lib/cursor.js +++ /dev/null @@ -1,33 +0,0 @@ -/*! - * mongoskin - cursor.js - * - * Copyright(c) 2011 - 2012 kissjs.org - * MIT Licensed - */ - -"use strict"; - -/** - * Module dependencies. - */ - -var Cursor = require('mongodb').Cursor; -var utils = require('./utils'); - -var SkinCursor = exports.SkinCursor = utils.makeSkinClass(Cursor); - -/** - * Retrieve mongodb.Cursor instance. - * - * @param {Function(err, cursor)} callback - * @return {SkinCursor} this - * @api public - */ -SkinCursor.prototype._open = function (callback) { - var self = this; - this._skin_collection.open(function (err, collection) { - if (err) return callback(err); - var args = self._find_args.concat([callback]); - collection.find.apply(collection, args); - }); -}; diff --git a/server/node_modules/monk/node_modules/mongoskin/lib/db.js b/server/node_modules/monk/node_modules/mongoskin/lib/db.js deleted file mode 100755 index 1e3a21e7..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/lib/db.js +++ /dev/null @@ -1,96 +0,0 @@ -/*! - * mongoskin - db.js - * - * Copyright(c) 2011 - 2012 kissjs.org - * Copyright(c) 2012 fengmk2 - * MIT Licensed - */ - -"use strict"; - -/** - * Module dependencies. - * TODO db.gridfs() - */ - -var mongodb = require('mongodb'); -var Db = mongodb.Db; -var MongoClient = mongodb.MongoClient; -var utils = require('./utils'); -var SkinAdmin = require('./admin').SkinAdmin; -var SkinCollection = require('./collection').SkinCollection; -var SkinGrid = require('./grid').SkinGrid; -var SkinGridStore = require('./grid_store').SkinGridStore; - -/** - * Constructor - */ -var SkinDb = exports.SkinDb = utils.makeSkinClass(Db, true); - -SkinDb.prototype._open = function(callback) { - // TODO authenticate support - if(this._native) { - this._native.open(callback); - } else if(this._connect_args) { - var args = this._connect_args.concat(callback); - MongoClient.connect.apply(MongoClient, args); - } -} - -/** - * Create or retrieval skin collection - * - * @param {String} name, the collection name. - * @param {Object} [options] collection options. - * @param {Function} [callback] - * @return {SkinCollection} - * @api public - */ -SkinDb.prototype.collection = function (name, options, callback) { - if(!callback && typeof options == 'function') { - callback = options; - options = undefined; - } - // Ooops, no extended mthods like findById etc. - // if(this.isOpen() && (!options || !options.strict) && !callback) { - // // mongodb now support collection without callback - // // see: http://mongodb.github.io/node-mongodb-native/api-generated/db.html#collection - // return this._native.collection(name, options); - // } - var collection = new SkinCollection(); - collection._skin_db = this; - collection._collection_args = [name, options]; - if (callback) { - collection.open(callback); - } - return collection; -}; - -/** - * @param {String} name the collection name - * @param {Object} [options] collection options - * @return {SkinCollection} collection - */ -SkinDb.prototype.bind = function (name, options) { - return this[name] = this.collection(name, options); -} - -SkinDb.prototype.admin = function () { - var skinAdmin = new SkinAdmin(); - skinAdmin._construct_args = [this]; - return skinAdmin; -} - -SkinDb.prototype.grid = function (fsName) { - var skinGrid = new SkinGrid(); - skinGrid._construct_args = [this, fsName]; - return skinGrid; -} - -SkinDb.prototype.gridStore = function () { - var skinGridStore = new SkinGridStore(); - var args = Array.prototype.slice.call(arguments); - args.unshift(this); - skinGridStore._construct_args = args; - return skinGridStore; -} diff --git a/server/node_modules/monk/node_modules/mongoskin/lib/grid.js b/server/node_modules/monk/node_modules/mongoskin/lib/grid.js deleted file mode 100755 index a4243675..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/lib/grid.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; - -var Grid = require('mongodb').Grid; -var makeSkinClass = require('./utils').makeSkinClass; - -var SkinGrid = exports.SkinGrid = makeSkinClass(Grid); - -SkinGrid.prototype._open = function(callback) { - var skin_db = this._construct_args[0]; - var fsName = this._construct_args[1]; - skin_db.open(function(err, p_db) { - if(err) return callback(err); - var grid = new Grid(p_db, fsName); - callback(null, grid); - }); -} diff --git a/server/node_modules/monk/node_modules/mongoskin/lib/grid_store.js b/server/node_modules/monk/node_modules/mongoskin/lib/grid_store.js deleted file mode 100755 index 21426740..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/lib/grid_store.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; - -var GridStore = require('mongodb').GridStore; -var makeSkinClass = require('./utils').makeSkinClass; - -var SkinGridStore = exports.SkinGridStore = makeSkinClass(GridStore); - -SkinGridStore.prototype._open = function(callback) { - var skin_db = this._construct_args[0]; - var args = this._construct_args.slice(1); - skin_db.open(function(err, p_db) { - if(err) return callback(err); - args = ([null, p_db]).concat(args); - var ctor = GridStore.bind.apply(GridStore, args); - var gridStore = new ctor(); - gridStore.open(callback); - }); -} - -function bindStaticMethod(methodName) { - SkinGridStore[methodName] = function(skindb) { - var args = Array.prototype.slice.call(arguments); - skindb.open(function(err, p_db) { - args[0] = p_db; - GridStore[methodName].apply(GridStore, args); - }); - } -} - -bindStaticMethod('exist'); -bindStaticMethod('list'); -bindStaticMethod('read'); -bindStaticMethod('readlines'); -bindStaticMethod('unlink'); diff --git a/server/node_modules/monk/node_modules/mongoskin/lib/helper.js b/server/node_modules/monk/node_modules/mongoskin/lib/helper.js deleted file mode 100755 index bf279ac0..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/lib/helper.js +++ /dev/null @@ -1,22 +0,0 @@ -var mongodb = require('mongodb'); -var ObjectID = mongodb.ObjectID; - -/** - * Convert to ObjectID. - * - * @param {String} hex - * @return {ObjectID} - */ -exports.toObjectID = function (hex) { - if (hex instanceof ObjectID) { - return hex; - } - if (!hex || hex.length !== 24) { - return hex; - } - return ObjectID.createFromHexString(hex); -}; - -exports.isObjectID = function (idstr) { - return ObjectID.isValid(idstr); -}; diff --git a/server/node_modules/monk/node_modules/mongoskin/lib/index.js b/server/node_modules/monk/node_modules/mongoskin/lib/index.js deleted file mode 100755 index f2ac4716..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/lib/index.js +++ /dev/null @@ -1,36 +0,0 @@ -/*! - * mongoskin - index.js - * - * Copyright(c) 2011 - 2012 kissjs.org - * MIT Licensed - */ - -"use strict"; - -/** - * Module dependencies. - */ - -var mongo = require('mongodb'); - -/* - * exports mongo classes ObjectID Long Code DbRef ... to mongoskin - */ -for (var key in mongo) { - exports[key] = mongo[key]; -} - -// exports.Foo = SkinFoo; -;['mongo_client', 'db', 'collection', 'cursor', 'admin', 'grid', 'grid_store'].forEach(function(modPath){ - var mod = require('./' + modPath); - for(var name in mod) { - if(name.indexOf('Skin') == 0) { - exports[name.substring(4)] = mod[name]; - } - } -}); - -exports.helper = require('./helper'); -exports.utils = require('./utils'); - -exports.db = exports.MongoClient.connect; diff --git a/server/node_modules/monk/node_modules/mongoskin/lib/mongo_client.js b/server/node_modules/monk/node_modules/mongoskin/lib/mongo_client.js deleted file mode 100755 index 14f4870e..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/lib/mongo_client.js +++ /dev/null @@ -1,15 +0,0 @@ -var mongodb = require('mongodb'); -var MongoClient = mongodb.MongoClient; -var utils = require('./utils'); - -var SkinDb = require('./db').SkinDb; - -var SkinMongoClient = utils.makeSkinClass(MongoClient, true); -exports.SkinMongoClient = SkinMongoClient; - -SkinMongoClient.connect = function() { - var args = [].slice.call(arguments); - var db = new SkinDb(); - db._connect_args = args; - return db; -} diff --git a/server/node_modules/monk/node_modules/mongoskin/lib/utils.js b/server/node_modules/monk/node_modules/mongoskin/lib/utils.js deleted file mode 100755 index dc0febe7..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/lib/utils.js +++ /dev/null @@ -1,205 +0,0 @@ -/*! - * mongoskin - utils.js - * - * Copyright(c) 2011 - 2012 kissjs.org - * Copyright(c) 2012 fengmk2 - * MIT Licensed - */ - -"use strict"; - -/** - * Module dependencies. - */ - -var __slice = Array.prototype.slice; -var EventEmitter = require('events').EventEmitter; -var constant = require('./constant'); -var STATE_CLOSE = constant.STATE_CLOSE; -var STATE_OPENNING = constant.STATE_OPENNING; -var STATE_OPEN = constant.STATE_OPEN; - -exports.makeSkinClass = function makeSkinClass(NativeClass, useNativeConstructor, isSingle) { - - function onError (err, args, name) { - var cb = args.pop(); - if (cb && typeof cb === 'function') { - cb(err); - } else { - console.error("Error occured with no callback to handle it while calling " + name, err); - } - }; - - var skinClassName = 'Skin' + NativeClass.name; - function SkinClass() { - var args = __slice.call(arguments); - this._construct_args = args; - if(useNativeConstructor && arguments.length > 0) { - args.unshift(null); - var ctor = NativeClass.bind.apply(NativeClass, args); - this._native = new ctor(); - } else { - this._native = null; - } - this._emitter = new EventEmitter(); - this._emitter.setMaxListeners(50); - this._state = STATE_CLOSE; - this._init && this._init(); - if(isSingle) { - for(var propName in SkinClass.prototype) { - if(propName[0] != '_') { - this[propName] = SkinClass.prototype[propName]; - } - } - var res = NativeClass.apply(this, args); - for(propName in res) { - this[propName] = res[propName]; - if(propName[0] != '_') bindObject(this, propName); - } - } - } - SkinClass._class_name = skinClassName; - - function bindObject(target, propName) { - if(target.hasOwnProperty(propName) && typeof target[propName] == 'function') { - var fn = target[propName]; - target[propName] = function() { - var args = __slice.apply(arguments); - if (target._state == STATE_OPEN) { - this._native[propName].apply(this._native, args); - } else { - this.open(function(err, p_native) { - if (err) { - onError(err, args, skinClassName + '.' + propName); - } else { - p_native[propName].apply(p_native, args); - } - }); - } - return this; - }.bind(target); - } - } - - function bindSkin(propName) { - var fn; - var desc = Object.getOwnPropertyDescriptor(NativeClass.prototype, propName); - if(!desc) { - // console.log('no desc', skinClassName, propName, desc); - try{ - fn = NativeClass.prototype[propName]; - } catch(e) {} - } else { - fn = desc.value; - } - if(typeof fn == 'function') { - SkinClass._bindMethod(propName); - } else if(desc) { - if (desc.get) { - SkinClass._bindGetter(propName); - } - if (desc.set) { - SkinClass._bindSetter(propName); - } - // } else { - // this will never be called, so comment it. - // console.log('no desc and no value', skinClassName, propName); - } - } - - SkinClass._bindMethod = function(propName) { - SkinClass.prototype[propName] = function() { - var args = __slice.apply(arguments); - if (this._state == STATE_OPEN) { - this._native[propName].apply(this._native, args); - } else { - this.open(function(err, p_native) { - if (err) { - onError(err, args, skinClassName + '.' + propName); - } else { - p_native[propName].apply(p_native, args); - } - }); - } - return this; - } - } - - SkinClass._bindGetter = function(propName) { - SkinClass.prototype.__defineGetter__(propName, function() { - return this._native && this._native[propName];// || this['_prop_' + propName]; - }); - } - - SkinClass._bindSetter = function(propName) { - SkinClass.prototype.__defineSetter__(propName, function(value) { - // this['_prop_' + propName] = value; - this.open(function(err, p_native) { - if(err) return onError(err, args, skinClassName + '.' + propName); - p_native[propName] = value; - }); - }); - } - - if(!isSingle) { - for(var propName in NativeClass.prototype) { - if(propName[0] != '_') bindSkin(propName); - } - } - - SkinClass.prototype.open = function(callback) { - switch (this._state) { - case STATE_OPEN: - callback(null, this._native); - break; - case STATE_OPENNING: - this._emitter.once('open', callback); - break; - default: - this._emitter.once('open', callback); - this._state = STATE_OPENNING; - var self = this; - this._open(function(err, p_native) { - if (err) { - self._state = STATE_CLOSE; - } else { - self._state = STATE_OPEN; - self._native = p_native; - } - self._emitter.emit('open', err, p_native); - }); - } - return this; - } - - SkinClass.prototype.close = function (callback) { - if (this._state === STATE_CLOSE) { - callback && callback(); - } else if (this._state === STATE_OPEN) { - this._state = STATE_CLOSE; - this._close(callback); - } else if (this._state === STATE_OPENNING) { - var self = this; - this._emitter.once('open', function (err, db) { - self.close(callback); - }); - } - this._native = null; - return this; - } - - SkinClass.prototype._close = function(callback) { - if(this._native.close) { - this._native.close(callback) - } else if(callback) { - callback(); - } - } - - SkinClass.prototype.isOpen = function() { - return this._state === STATE_OPEN; - } - - return SkinClass; - -} diff --git a/server/node_modules/monk/node_modules/mongoskin/package.json b/server/node_modules/monk/node_modules/mongoskin/package.json deleted file mode 100755 index c06f4731..00000000 --- a/server/node_modules/monk/node_modules/mongoskin/package.json +++ /dev/null @@ -1,145 +0,0 @@ -{ - "name": "mongoskin", - "description": "The future layer above node-mongodb-native", - "version": "1.4.13", - "author": { - "name": "Gui Lin", - "email": "guileen@gmail.com" - }, - "homepage": "https://github.com/kissjs/node-mongoskin", - "repository": { - "type": "git", - "url": "git://github.com/kissjs/node-mongoskin.git" - }, - "bugs": { - "url": "https://github.com/kissjs/node-mongoskin/issues" - }, - "main": "./index.js", - "keywords": [ - "mongodb", - "database", - "nosql" - ], - "engines": { - "node": ">= 0.4.0" - }, - "peerDependencies": { - "mongodb": "~1.4" - }, - "devDependencies": { - "mocha": "~1.17.1", - "blanket": "~1.1.6", - "coveralls": "~2.10.0", - "mocha-lcov-reporter": "0.0.1", - "travis-cov": "~0.2.5", - "mongodb": "~1.4", - "should": "~3.1.2" - }, - "config": { - "blanket": { - "pattern": "mongoskin/lib" - }, - "travis-cov": { - "threshold": 95 - } - }, - "scripts": { - "test": "mocha -R travis-cov" - }, - "directories": { - "example": "./examples", - "lib": "./lib/mongoskin" - }, - "license": "MIT", - "contributors": [ - { - "name": "Gui Lin", - "email": "guileen@gmail.com", - "url": "https://github.com/guileen" - }, - { - "name": "François de Metz", - "email": "francois@2metz.fr", - "url": "https://github.com/francois2metz" - }, - { - "name": "fengmk2", - "email": "fengmk2@gmail.com", - "url": "http://fengmk2.github.com" - }, - { - "name": "Quang Van", - "email": "quangvvv@gmail.com", - "url": "https://github.com/quangv" - }, - { - "name": "Matt Perpick", - "email": "clutchski@gmail.com", - "url": "https://github.com/clutchski" - }, - { - "name": "humanchimp", - "email": "morphcham@gmail.com", - "url": "https://github.com/humanchimp" - }, - { - "name": "Joe Faber", - "email": "joe.faber@mandiant.com", - "url": "https://github.com/jlfaber" - }, - { - "name": "Harvey McQueen", - "email": "hmcqueen@gmail.com", - "url": "https://github.com/hmcqueen" - }, - { - "name": "Paul Gebheim", - "email": "pgebheim@monkeyinferno.com", - "url": "https://github.com/paulirish" - }, - { - "name": "Aneil Mallavarapu", - "email": "aneil@blipboard.com", - "url": "https://github.com/amallavarapu" - }, - { - "name": "wmertens", - "email": "Wout.Mertens@gmail.com", - "url": "https://github.com/wmertens" - }, - { - "name": "Rakshit Menpara", - "email": "deltasquare4@gmail.com", - "url": "https://github.com/deltasquare4" - } - ], - "gitHead": "8dcf669ff808463191033cc1e3917caa2bc41984", - "_id": "mongoskin@1.4.13", - "_shasum": "1deec5b5dcc25180a9a19c59956c098f8c12ee7d", - "_from": "mongoskin@1.4.13", - "_npmVersion": "2.5.1", - "_nodeVersion": "0.12.0", - "_npmUser": { - "name": "vkarpov15", - "email": "val@karpov.io" - }, - "maintainers": [ - { - "name": "guileen", - "email": "guileen@gmail.com" - }, - { - "name": "fengmk2", - "email": "fengmk2@gmail.com" - }, - { - "name": "vkarpov15", - "email": "val@karpov.io" - } - ], - "dist": { - "shasum": "1deec5b5dcc25180a9a19c59956c098f8c12ee7d", - "tarball": "http://registry.npmjs.org/mongoskin/-/mongoskin-1.4.13.tgz" - }, - "_resolved": "https://registry.npmjs.org/mongoskin/-/mongoskin-1.4.13.tgz" -} diff --git a/server/node_modules/monk/node_modules/mpromise/.npmignore b/server/node_modules/monk/node_modules/mpromise/.npmignore deleted file mode 100755 index e86496f9..00000000 --- a/server/node_modules/monk/node_modules/mpromise/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -*.sw* -node_modules/ -.DS_Store -.idea \ No newline at end of file diff --git a/server/node_modules/monk/node_modules/mpromise/.travis.yml b/server/node_modules/monk/node_modules/mpromise/.travis.yml deleted file mode 100755 index 09d3ef37..00000000 --- a/server/node_modules/monk/node_modules/mpromise/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.8 - - 0.10 diff --git a/server/node_modules/monk/node_modules/mpromise/History.md b/server/node_modules/monk/node_modules/mpromise/History.md deleted file mode 100755 index a64788e8..00000000 --- a/server/node_modules/monk/node_modules/mpromise/History.md +++ /dev/null @@ -1,74 +0,0 @@ -0.5.1 / 2014-01-20 -================== - - * fixed; `end` is much more consistent (especially for `then` chains) - -0.4.4 / 2014-01-20 -================== - - * fixed; `end` is much more consistent (especially for `then` chains) - -0.4.3 / 2013-12-17 -================== - - * fixed; non-A+ behavior on fulfill and reject [lbeschastny](https://github.com/lbeschastny) - * tests; simplified harness + compatible with travis + compatible with windows - -0.5.0 / 2013-12-14 -================== - - * fixed; non-A+ behavior on fulfill and reject [lbeschastny](https://github.com/lbeschastny) - * tests; simplified harness + compatible with travis + compatible with windows - -0.4.2 / 2013-11-26 -================== - - * fixed; enter the domain only if not the present domain - * added; `end` returns the promise - -0.4.1 / 2013-10-26 -================== - - * Add `all` - * Longjohn for easier debugging - * can end a promise chain with an error handler - * Add ```chain``` - -0.4.0 / 2013-10-24 -================== - - * fixed; now plays nice with domains #3 [refack](https://github.com/refack) - * updated; compatibility for Promises A+ 2.0.0 [refack](https://github.com/refack) - * updated; guard against invalid arguments [refack](https://github.com/refack) - -0.3.0 / 2013-07-25 -================== - - * updated; sliced to 0.0.5 - * fixed; then is passed all fulfillment values - * use setImmediate if available - * conform to Promises A+ 1.1 - -0.2.1 / 2013-02-09 -================== - - * fixed; conformancy with A+ 1.2 - -0.2.0 / 2013-01-09 -================== - - * added; .end() - * fixed; only catch handler executions - -0.1.0 / 2013-01-08 -================== - - * cleaned up API - * customizable event names - * docs - -0.0.1 / 2013-01-07 -================== - - * original release - diff --git a/server/node_modules/monk/node_modules/mpromise/LICENSE b/server/node_modules/monk/node_modules/mpromise/LICENSE deleted file mode 100755 index 38c529da..00000000 --- a/server/node_modules/monk/node_modules/mpromise/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.com) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/monk/node_modules/mpromise/README.md b/server/node_modules/monk/node_modules/mpromise/README.md deleted file mode 100755 index 2906f563..00000000 --- a/server/node_modules/monk/node_modules/mpromise/README.md +++ /dev/null @@ -1,224 +0,0 @@ -#mpromise -========== - -[![Build Status](https://travis-ci.org/aheckmann/mpromise.png)](https://travis-ci.org/aheckmann/mpromise) - -A [promises/A+](https://github.com/promises-aplus/promises-spec) conformant implementation, written for [mongoose](http://mongoosejs.com). - -## installation - -``` -$ npm install mpromise -``` - -## docs - -An `mpromise` can be in any of three states, pending, fulfilled (success), or rejected (error). Once it is either fulfilled or rejected it's state can no longer be changed. - -The exports object is the Promise constructor. - -```js -var Promise = require('mpromise'); -``` - -The constructor accepts an optional function which is executed when the promise is first resolved (either fulfilled or rejected). - -```js -var promise = new Promise(fn); -``` - -This is the same as passing the `fn` to `onResolve` directly. - -```js -var promise = new Promise; -promise.onResolve(function (err, args..) { - ... -}); -``` - -### Methods - -####fulfill - -Fulfilling a promise with values: - -```js -var promise = new Promise; -promise.fulfill(args...); -``` - -If the promise has already been fulfilled or rejected, no action is taken. - -####reject - -Rejecting a promise with a reason: - -```js -var promise = new Promise; -promise.reject(reason); -``` - -If the promise has already been fulfilled or rejected, no action is taken. - -####resolve - -Node.js callback style promise resolution `(err, args...)`: - -```js -var promise = new Promise; -promise.resolve([reason], [arg1, arg2, ...]); -``` - -If the promise has already been fulfilled or rejected, no action is taken. - -####onFulfill - -To register a function for execution when the promise is fulfilled, pass it to `onFulfill`. When executed it will receive the arguments passed to `fulfill()`. - -```js -var promise = new Promise; -promise.onFulfill(function (a, b) { - assert.equal(3, a + b); -}); -promise.fulfill(1, 2); -``` - -The function will only be called once when the promise is fulfilled, never when rejected. - -Registering a function with `onFulfill` after the promise has already been fulfilled results in the immediate execution of the function with the original arguments used to fulfill the promise. - -```js -var promise = new Promise; -promise.fulfill(" :D "); -promise.onFulfill(function (arg) { - console.log(arg); // logs " :D " -}) -``` - -####onReject - -To register a function for execution when the promise is rejected, pass it to `onReject`. When executed it will receive the argument passed to `reject()`. - -```js -var promise = new Promise; -promise.onReject(function (reason) { - assert.equal('sad', reason); -}); -promise.reject('sad'); -``` - -The function will only be called once when the promise is rejected, never when fulfilled. - -Registering a function with `onReject` after the promise has already been rejected results in the immediate execution of the function with the original argument used to reject the promise. - -```js -var promise = new Promise; -promise.reject(" :( "); -promise.onReject(function (reason) { - console.log(reason); // logs " :( " -}) -``` - -####onResolve - -Allows registration of node.js style callbacks `(err, args..)` to handle either promise resolution type (fulfill or reject). - -```js -// fulfillment -var promise = new Promise; -promise.onResolve(function (err, a, b) { - console.log(a + b); // logs 3 -}); -promise.fulfill(1, 2); - -// rejection -var promise = new Promise; -promise.onResolve(function (err) { - if (err) { - console.log(err.message); // logs "failed" - } -}); -promise.reject(new Error('failed')); -``` - -####then - -Creates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick. - -Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification and passes its [tests](https://github.com/promises-aplus/promises-tests). - -```js -// promise.then(onFulfill, onReject); - -var p = new Promise; - -p.then(function (arg) { - return arg + 1; -}).then(function (arg) { - throw new Error(arg + ' is an error!'); -}).then(null, function (err) { - assert.ok(err instanceof Error); - assert.equal('2 is an error', err.message); -}); -p.fullfill(1); -``` - -####end - -Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception be rethrown. -You can pass an OnReject handler to `end` so that exceptions will be handled (like a final catch clause); -This method returns it's promise for easy use with `return`. - -```js -var p = new Promise; -p.then(function(){ throw new Error('shucks') }); -setTimeout(function () { - p.fulfill(); - // error was caught and swallowed by the promise returned from - // p.then(). we either have to always register handlers on - // the returned promises or we can do the following... -}, 10); - -// this time we use .end() which prevents catching thrown errors -var p = new Promise; -setTimeout(function () { - p.fulfill(); // throws "shucks" -}, 10); -return p.then(function(){ throw new Error('shucks') }).end(); // <-- -``` - - -### chain - -Allows direct promise to promise chaining (especially useful by a outside aggregating function). It doesn't use the asynchronous `resolve` algorithm and so excepts only another Promise as it's argument. - -```js -function makeMeAPromise(i) { - var p = new Promise; - p.fulfill(i); - return p; -} - -var returnPromise = initialPromise = new Promise; -for (i=0; i<10; ++i) - returnPromise = returnPromise.chain(makeMeAPromise(i)); - -initialPromise.fulfill(); -return returnPromise; -``` - -###Event names - -If you'd like to alter this implementations event names used to signify success and failure you may do so by setting `Promise.SUCCESS` or `Promise.FAILURE` respectively. - -```js -Promise.SUCCESS = 'complete'; -Promise.FAILURE = 'err'; -``` - -###Luke, use the Source -For more ideas read the [source](https://github.com/aheckmann/mpromise/blob/master/lib), [tests](https://github.com/aheckmann/mpromise/blob/master/test), or the [mongoose implementation](https://github.com/LearnBoost/mongoose/blob/3.6x/lib/promise.js). - -## license - -[MIT](https://github.com/aheckmann/mpromise/blob/master/LICENSE) diff --git a/server/node_modules/monk/node_modules/mpromise/index.js b/server/node_modules/monk/node_modules/mpromise/index.js deleted file mode 100755 index 0b3669d7..00000000 --- a/server/node_modules/monk/node_modules/mpromise/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = exports = require('./lib/promise'); diff --git a/server/node_modules/monk/node_modules/mpromise/lib/promise.js b/server/node_modules/monk/node_modules/mpromise/lib/promise.js deleted file mode 100755 index 04eb52a5..00000000 --- a/server/node_modules/monk/node_modules/mpromise/lib/promise.js +++ /dev/null @@ -1,459 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -var slice = function (arr, start, end) { - return Array.prototype.slice.call(arr, start, end) -}; -var EventEmitter = require('events').EventEmitter; - -/** - * Promise constructor. - * - * _NOTE: The success and failure event names can be overridden by setting `Promise.SUCCESS` and `Promise.FAILURE` respectively._ - * - * @param {Function} back a function that accepts `fn(err, ...){}` as signature - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `reject`: Emits when the promise is rejected (event name may be overridden) - * @event `fulfill`: Emits when the promise is fulfilled (event name may be overridden) - * @api public - */ - -function Promise(back) { - EventEmitter.call(this); - - this.emitted = {}; - this.ended = false; - if ('function' == typeof back) - this.onResolve(back); -} - -/*! - * event names - */ - -Promise.SUCCESS = 'fulfill'; -Promise.FAILURE = 'reject'; - -/*! - * Inherits from EventEmitter. - */ - -Promise.prototype.__proto__ = EventEmitter.prototype; - -/** - * Adds `listener` to the `event`. - * - * If `event` is either the success or failure event and the event has already been emitted, the`listener` is called immediately and passed the results of the original emitted event. - * - * @param {String} event - * @param {Function} callback - * @return {Promise} this - * @api public - */ - -Promise.prototype.on = function (event, callback) { - if (this.emitted[event]) - callback.apply(this, this.emitted[event]); - else - EventEmitter.prototype.on.call(this, event, callback); - - return this; -} - -/** - * Keeps track of emitted events to run them on `on`. - * - * @api private - */ - -Promise.prototype.emit = function (event) { - // ensures a promise can't be fulfill() or reject() more than once - var success = this.constructor.SUCCESS; - var failure = this.constructor.FAILURE; - - if (event == success || event == failure) { - if (this.emitted[success] || this.emitted[failure]) { - return this; - } - this.emitted[event] = slice(arguments, 1); - } - - return EventEmitter.prototype.emit.apply(this, arguments); -} - -/** - * Fulfills this promise with passed arguments. - * - * If this promise has already been fulfilled or rejected, no action is taken. - * - * @api public - */ - -Promise.prototype.fulfill = function () { - var args = slice(arguments); - return this.emit.apply(this, [this.constructor.SUCCESS].concat(args)); -} - -/** - * Rejects this promise with `reason`. - * - * If this promise has already been fulfilled or rejected, no action is taken. - * - * @api public - * @param {Object|String} reason - * @return {Promise} this - */ - -Promise.prototype.reject = function (reason) { - if (this.ended && !this.hasRejectListeners()) throw reason; - return this.emit(this.constructor.FAILURE, reason); -} - -/** - * Resolves this promise to a rejected state if `err` is passed or - * fulfilled state if no `err` is passed. - * - * @param {Error} [err] error or null - * @param {Object} [val] value to fulfill the promise with - * @api public - */ - -Promise.prototype.resolve = function (err, val) { - if (err) return this.reject(err); - return this.fulfill(val); -} - -/** - * Adds a listener to the SUCCESS event. - * - * @return {Promise} this - * @api public - */ - -Promise.prototype.onFulfill = function (fn) { - if (!fn) return this; - if ('function' != typeof fn) throw new TypeError("fn should be a function"); - return this.on(this.constructor.SUCCESS, fn); -} - -Promise.prototype.hasRejectListeners = function () { - return this.listeners(this.constructor.FAILURE).length > 0; -}; -/** - * Adds a listener to the FAILURE event. - * - * @return {Promise} this - * @api public - */ - -Promise.prototype.onReject = function (fn) { - if (!fn) return this; - if ('function' != typeof fn) throw new TypeError("fn should be a function"); - return this.on(this.constructor.FAILURE, fn); -} - -/** - * Adds a single function as a listener to both SUCCESS and FAILURE. - * - * It will be executed with traditional node.js argument position: - * function (err, args...) {} - * - * @param {Function} fn - * @return {Promise} this - */ - -Promise.prototype.onResolve = function (fn) { - if (!fn) return this; - if ('function' != typeof fn) throw new TypeError("fn should be a function"); - - this.on(this.constructor.FAILURE, function (err) { - fn.apply(this, [err]); - }); - - this.on(this.constructor.SUCCESS, function () { - var args = slice(arguments); - fn.apply(this, [null].concat(args)); - }); - - return this; -} - -/** - * Creates a new promise and returns it. If `onFulfill` or - * `onReject` are passed, they are added as SUCCESS/ERROR callbacks - * to this promise after the next tick. - * - * Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification. Read for more detail how to use this method. - * - * ####Example: - * - * var p = new Promise; - * p.then(function (arg) { - * return arg + 1; - * }).then(function (arg) { - * throw new Error(arg + ' is an error!'); - * }).then(null, function (err) { - * assert.ok(err instanceof Error); - * assert.equal('2 is an error', err.message); - * }); - * p.complete(1); - * - * @see promises-A+ https://github.com/promises-aplus/promises-spec - * @param {Function} onFulFill - * @param {Function} [onReject] - * @return {Promise} newPromise - */ - -Promise.prototype.then = function (onFulfill, onReject) { - var self = this - , retPromise = new Promise; - - if ('function' == typeof onReject) { - self.onReject(handler(retPromise, onReject)); - } else { - self.onReject(retPromise.reject.bind(retPromise)); - } - if ('function' == typeof onFulfill) { - self.onFulfill(handler(retPromise, onFulfill)); - } else { - self.onFulfill(retPromise.fulfill.bind(retPromise)); - } - - return retPromise; -}; - - -function handler(retPromise, fn) { - return function handler() { - var args = arguments; - process.nextTick( - function in_the_handler() { - if (retPromise.domain && retPromise.domain !== process.domain) retPromise.domain.enter(); - var x; - - try { - x = fn.apply(undefined, args); - } catch (err) { - return retPromise.reject(err); - } - - resolve(retPromise, x); - return; - } - ); - } -} - -function resolve(promise, x) { - var then; - var type; - var done; - var reject_; - var resolve_; - - type = typeof x; - if ('undefined' == type) { - return promise.fulfill(x); - } - - if (promise === x) { - return promise.reject(new TypeError("promise and x are the same")); - } - - if (null != x) { - - if ('object' == type || 'function' == type) { - try { - then = x.then; - } catch (err) { - return promise.reject(err); - } - - if ('function' == typeof then) { - try { - resolve_ = function () {var args = slice(arguments); resolve.apply(this, [promise].concat(args));}; - reject_ = promise.reject.bind(promise); - done = false; - return then.call( - x - , function fulfill() { - if (done) return; - done = true; - return resolve_.apply(this, arguments); - } - , function reject() { - if (done) return; - done = true; - return reject_.apply(this, arguments); - }) - } catch (err) { - if (done) return; - done = true; - if (promise.ended) throw err; - return promise.reject(err); - } - } - } - } - - promise.fulfill(x); -} - -/** - * Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught. - * - * ####Example: - * - * var p = new Promise; - * p.then(function(){ throw new Error('shucks') }); - * setTimeout(function () { - * p.fulfill(); - * // error was caught and swallowed by the promise returned from - * // p.then(). we either have to always register handlers on - * // the returned promises or we can do the following... - * }, 10); - * - * // this time we use .end() which prevents catching thrown errors - * var p = new Promise; - * var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <-- - * setTimeout(function () { - * p.fulfill(); // throws "shucks" - * }, 10); - * - * @api public - * @param {Function} [onReject] - * @return {Promise} this - */ - -Promise.prototype.end = function (onReject) { - this.onReject(onReject); - this.ended = true; - return this; -}; - - -/** - * A debug utility function that adds handlers to a promise that will log some output to the `console` - * - * ####Example: - * - * var p = new Promise; - * p.then(function(){ throw new Error('shucks') }); - * setTimeout(function () { - * p.fulfill(); - * // error was caught and swallowed by the promise returned from - * // p.then(). we either have to always register handlers on - * // the returned promises or we can do the following... - * }, 10); - * - * // this time we use .end() which prevents catching thrown errors - * var p = new Promise; - * var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <-- - * setTimeout(function () { - * p.fulfill(); // throws "shucks" - * }, 10); - * - * @api public - * @param {Promise} p - * @param {String} name - * @return {Promise} this - */ - -Promise.trace = function (p, name) { - p.then( - function () { - console.log("%s fulfill %j", name, slice(arguments)); - } - , - function () { - console.log("%s reject %j", name, slice(arguments)); - } - ) -}; - - -Promise.prototype.chain = function (p2) { - var p1 = this; - p1.onFulfill(p2.fulfill.bind(p2)); - p1.onReject(p2.reject.bind(p2)); - return p2; -}; - - -Promise.deferred = function () { - var p = new Promise; - return { - promise: p, - reject: p.reject.bind(p), - fulfill: p.fulfill.bind(p), - callback: p.resolve.bind(p) - } -}; - - -/*! - * Module exports. - */ - -Promise.prototype.all = function (promiseOfArr) { - var pRet = new Promise; - this.then(promiseOfArr).then( - function (promiseArr) { - var count = 0; - var ret = []; - var errSentinel; - if (!promiseArr.length) pRet.resolve(); - promiseArr.forEach(function (promise, index) { - if (errSentinel) return; - count++; - promise.then( - function (val) { - if (errSentinel) return; - ret[index] = val; - --count; - if (count == 0) pRet.fulfill(ret); - }, - function (err) { - if (errSentinel) return; - errSentinel = err; - pRet.reject(err); - } - ); - }); - return pRet; - } - , pRet.reject.bind(pRet) - ); - return pRet; -}; - - -Promise.hook = function(arr) { - var p1 = new Promise; - var pFinal = new Promise; - var signalP = function () { - --count; - if (count == 0) - pFinal.fulfill(); - return pFinal; - }; - var count = 1; - var ps = p1; - arr.forEach(function (hook) { - ps = ps.then( - function () { - var p = new Promise; - count++; - hook(p.resolve.bind(p), signalP); - return p; - } - ) - }); - ps = ps.then(signalP); - p1.resolve(); - return ps; -}; -module.exports = Promise; diff --git a/server/node_modules/monk/node_modules/mpromise/package.json b/server/node_modules/monk/node_modules/mpromise/package.json deleted file mode 100755 index 5561fee1..00000000 --- a/server/node_modules/monk/node_modules/mpromise/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "mpromise", - "version": "0.5.1", - "description": "Promises A+ conformant implementation", - "main": "index.js", - "scripts": { - "test": "node node_modules/mocha/bin/_mocha" - }, - "devDependencies": { - "longjohn": "0.2.2", - "promises-aplus-tests": "2.0.3", - "mocha": "1.13.0" - }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mpromise" - }, - "keywords": [ - "promise", - "mongoose", - "aplus", - "a+", - "plus" - ], - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "license": "MIT", - "bugs": { - "url": "https://github.com/aheckmann/mpromise/issues" - }, - "homepage": "https://github.com/aheckmann/mpromise", - "_id": "mpromise@0.5.1", - "dist": { - "shasum": "ef1890a5c24e8b239f009474f0a65a040cca0e61", - "tarball": "http://registry.npmjs.org/mpromise/-/mpromise-0.5.1.tgz" - }, - "_from": "mpromise@0.5.1", - "_npmVersion": "1.3.23", - "_npmUser": { - "name": "refack", - "email": "refael@empeeric.com" - }, - "maintainers": [ - { - "name": "refack", - "email": "refael@empeeric.com" - } - ], - "directories": {}, - "_shasum": "ef1890a5c24e8b239f009474f0a65a040cca0e61", - "_resolved": "https://registry.npmjs.org/mpromise/-/mpromise-0.5.1.tgz" -} diff --git a/server/node_modules/monk/node_modules/mpromise/test/promise.domain.test.js b/server/node_modules/monk/node_modules/mpromise/test/promise.domain.test.js deleted file mode 100755 index 579c462e..00000000 --- a/server/node_modules/monk/node_modules/mpromise/test/promise.domain.test.js +++ /dev/null @@ -1,32 +0,0 @@ -var Promise = require('../') - , Domain = require('domain') - , assert = require('assert'); - -var next = 'function' == typeof setImmediate - ? setImmediate - : process.nextTick; - -describe("domains", function () { - it("exceptions should not breakout of domain bounderies", function (done) { - if (process.version.indexOf('v0.8') == 0) return done(); - var d = Domain.create(); - d.once('error', function (err) { - assert.equal(err.message, 'gaga'); - done() - }); - - var p = new Promise(); - - d.run(function () { - p.then(function () { - - }).then(function () { - throw new Error('gaga'); - }).end(); - }); - - next(function () { - p.fulfill(); - }) - }); -}); diff --git a/server/node_modules/monk/node_modules/mpromise/test/promise.test.js b/server/node_modules/monk/node_modules/mpromise/test/promise.test.js deleted file mode 100755 index e9643c7a..00000000 --- a/server/node_modules/monk/node_modules/mpromise/test/promise.test.js +++ /dev/null @@ -1,494 +0,0 @@ -/*global describe,it */ -if (process.version.indexOf('v0.11') == -1) require("longjohn"); -/** - * Module dependencies. - */ - -var assert = require('assert'); -var Promise = require('../'); - -/** - * Test. - */ - -describe('promise', function(){ - it('events fire right after fulfill()', function(done){ - var promise = new Promise() - , called = 0; - - promise.on('fulfill', function (a, b) { - assert.equal(a, '1'); - assert.equal(b, '2'); - called++; - }); - - promise.fulfill('1', '2'); - - promise.on('fulfill', function (a, b) { - assert.equal(a, '1'); - assert.equal(b, '2'); - called++; - }); - - assert.equal(2, called); - done(); - }); - - it('events fire right after reject()', function(done){ - var promise = new Promise() - , called = 0; - - promise.on('reject', function (err) { - assert.ok(err instanceof Error); - called++; - }); - - promise.reject(new Error('booyah')); - - promise.on('reject', function (err) { - assert.ok(err instanceof Error); - called++; - }); - - assert.equal(2, called); - done() - }); - - describe('onResolve()', function(){ - it('from constructor works', function(done){ - var called = 0; - - var promise = new Promise(function (err) { - assert.ok(err instanceof Error); - called++; - }) - - promise.reject(new Error('dawg')); - - assert.equal(1, called); - done(); - }); - - it('after fulfill()', function(done){ - var promise = new Promise() - , called = 0; - - promise.fulfill('woot'); - - promise.onResolve(function (err, data){ - assert.equal(data,'woot'); - called++; - }); - - promise.onResolve(function (err, data){ - assert.strictEqual(err, null); - called++; - }); - - assert.equal(2, called); - done(); - }) - }); - - describe('onFulfill shortcut', function(){ - it('works', function(done){ - var promise = new Promise() - , called = 0; - - promise.onFulfill(function (woot) { - assert.strictEqual(woot, undefined); - called++; - }); - - promise.fulfill(); - - assert.equal(1, called); - done(); - }) - }) - - describe('onReject shortcut', function(){ - it('works', function(done){ - var promise = new Promise() - , called = 0; - - promise.onReject(function (err) { - assert.ok(err instanceof Error); - called++; - }); - - promise.reject(new Error); - assert.equal(1, called); - done(); - }) - }); - - describe('return values', function(){ - it('on()', function(done){ - var promise = new Promise() - assert.ok(promise.on('jump', function(){}) instanceof Promise); - done() - }); - - it('onFulfill()', function(done){ - var promise = new Promise() - assert.ok(promise.onFulfill(function(){}) instanceof Promise); - done(); - }) - it('onReject()', function(done){ - var promise = new Promise() - assert.ok(promise.onReject(function(){}) instanceof Promise); - done(); - }) - it('onResolve()', function(done){ - var promise = new Promise() - assert.ok(promise.onResolve(function(){}) instanceof Promise); - done(); - }) - }) - - describe('casting errors', function(){ - describe('reject()', function(){ - it('does not cast arguments to Error', function(done){ - var p = new Promise(function (err, arg) { - assert.equal(3, err); - done(); - }); - - p.reject(3); - }) - }) - }) - - describe('then', function(){ - describe('catching', function(){ - it('should not catch returned promise fulfillments', function(done){ - var errorSentinal - , p = new Promise - , p2 = p.then(function () { throw errorSentinal = new Error("boo!") }); - - p.fulfill(); - done(); - }); - - - it('should not catch returned promise fulfillments even async', function (done) { - var errorSentinal - , p = new Promise - , p2 = p.then(function () { throw errorSentinal = new Error("boo!") }); - - setTimeout(function () { - p.fulfill(); - done(); - }, 10); - }); - - - it('can be disabled using .end()', function(done){ - if (process.version.indexOf('v0.8') == 0) return done(); - var errorSentinal - , overTimeout - , domain = require('domain').create(); - - domain.once('error', function (err) { - assert(err, errorSentinal); - clearTimeout(overTimeout); - done() - }); - - domain.run(function () { - var p = new Promise; - var p2 = p.then(function () { - throw errorSentinal = new Error('shucks') - }); - p2.end(); - - p.fulfill(); - }); - overTimeout = setTimeout(function () { done(new Error('error was swallowed')); }, 10); - }); - - - it('can be disabled using .end() even when async', function (done) { - if (process.version.indexOf('v0.8') == 0) return done(); - var errorSentinal - , overTimeout - , domain = require('domain').create(); - - domain.on('error', function (err) { - assert(err, errorSentinal); - clearTimeout(overTimeout); - done() - }); - - domain.run(function () { - var p = new Promise; - var p2 = p.then(function () { - throw errorSentinal = new Error("boo!") - }); - p2.end(); - - setTimeout(function () {p.fulfill();}, 10); - }); - overTimeout = setTimeout(function () { done(new Error('error was swallowed')); }, 20); - }); - - - it('can be handled using .end() so no throwing', function (done) { - var errorSentinal - , overTimeout - , domain = require('domain').create(); - - domain.run(function () { - var p = new Promise; - var p2 = p.then(function () { - throw errorSentinal = new Error("boo!") - }); - p2.end(function (err) { - assert.equal(err, errorSentinal); - clearTimeout(overTimeout); - done() - }); - - setTimeout(function () {p.fulfill();}, 10); - }); - overTimeout = setTimeout(function () { done(new Error('error was swallowed')); }, 20); - }); - - }); - - it('persistent', function(done){ - var p = new Promise - v = null; - - function ensure (val) { - v = v || val; - assert.equal(v, val); - } - - function guard () { - throw new Error('onReject should not be called'); - } - - p.then(ensure, guard).end(); - - p.fulfill('foo'); - p.fulfill('bar'); - p.reject(new Error('baz')); - - p.then(ensure, guard).end(); - - setTimeout(done, 0); - }); - - - it('accepts multiple completion values', function(done){ - var p = new Promise; - - p.then(function (a, b) { - assert.equal(2, arguments.length); - assert.equal('hi', a); - assert.equal(4, b); - done(); - }, done).end(); - - p.fulfill('hi', 4); - }) - }); - - - describe('end', function () { - it("should return the promise", function (done) { - var p = new Promise; - var p1 = p.end(); - assert.equal(p, p1); - done(); - }); - - - it("should throw for chain", function (done) { - var p = new Promise; - p.then().then().then().then().end(); - try { - p.reject('bad'); - } catch (e) { - done(); - } - }); - - - it("should not throw for chain with reject handler", function (done) { - var p = new Promise; - p.then().then().then().then().end(function () { - done(); - }); - try { - p.reject('bad'); - } catch (e) { - done(e); - } - }); - }); - - - describe('chain', function () { - it('should propagate fulfillment', function (done) { - var varSentinel = {a:'a'}; - var p1 = new Promise; - var p2 = p1.chain(new Promise(function (err, doc) { - assert.equal(doc, varSentinel); - done(); - })); - p1.fulfill(varSentinel); - }); - - - it('should propagate rejection', function (done) { - var e = new Error("gaga"); - var p1 = new Promise; - var p2 = p1.chain(new Promise(function (err) { - assert.equal(err, e); - done(); - })); - p1.reject(e); - }); - - - it('should propagate resolution err', function (done) { - var e = new Error("gaga"); - var p1 = new Promise; - var p2 = p1.chain(new Promise(function (err) { - assert.equal(err, e); - done(); - })); - p1.resolve(e); - }); - - - it('should propagate resolution val', function (done) { - var varSentinel = {a:'a'}; - var p1 = new Promise; - var p2 = p1.chain(new Promise(function (err, val) { - assert.equal(val, varSentinel); - done(); - })); - p1.resolve(null, varSentinel); - }) - }); - - - describe("all", function () { - it("works", function (done) { - var count = 0; - var p = new Promise; - var p2 = p.all(function () { - return [ - (function () {var p = new Promise(); count++ ;p.resolve(); return p;})() - , (function () {var p = new Promise(); count++ ;p.resolve(); return p;})() - ]; - }); - p2.then(function () { - assert.equal(count, 2); - done(); - }); - p.resolve(); - }); - - - it("handles rejects", function (done) { - var count = 0; - var p = new Promise; - var p2 = p.all(function () { - return [ - (function () {var p = new Promise(); count++; p.resolve(); return p;})() - , (function () {var p = new Promise(); count++; throw new Error("gaga");})() - ]; - }); - p2.onReject(function (err) { - assert(err.message, "gaga"); - assert.equal(count, 2); - done(); - }); - p.resolve(); - }); - }); - - - describe("deferred", function () { - it("works", function (done) { - var d = Promise.deferred(); - assert.ok(d.promise instanceof Promise); - assert.ok(d.reject instanceof Function); - assert.ok(d.fulfill instanceof Function); - assert.ok(d.callback instanceof Function); - done(); - }); - }); - - - describe("hook", function () { - it("works", function (done) { - var run = 0; - var l1 = function (ser, par) { - run++; - ser(); - par(); - }; - Promise.hook([l1, l1, l1]).then(function () { - assert(run, 3); - done(); - }) - - }); - - - it("works with async serial hooks", function (done) { - this.timeout(800); - var run = 0; - var l1 = function (ser, par) { - run++; - setTimeout(function () {ser();}, 200); - par(); - }; - Promise.hook([l1, l1, l1]).then(function () { - assert(run, 3); - done(); - }) - }); - - - it("works with async parallel hooks", function (done) { - this.timeout(400); - var run = 0; - var l1 = function (ser, par) { - run++; - ser(); - setTimeout(function () {par();}, 200); - }; - Promise.hook([l1, l1, l1]).then(function () { - assert(run, 3); - done(); - }) - }); - - - it("catches errors in hook logic", function (done) { - var run = 0; - var l1 = function (ser, par) { - run++; - ser(); - par(); - }; - var l2 = function (ser, par) { - run++; - ser(); - par(); - throw new Error("err") - }; - Promise.hook([l1, l2, l1]).end(function (err) { - assert(run, 2); - done(); - }); - }); - }); -}); diff --git a/server/node_modules/monk/node_modules/mpromise/test/promises.Aplus.js b/server/node_modules/monk/node_modules/mpromise/test/promises.Aplus.js deleted file mode 100755 index 271e6aee..00000000 --- a/server/node_modules/monk/node_modules/mpromise/test/promises.Aplus.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Module dependencies. - */ - -var Promise = require('../lib/promise'); -var aplus = require('promises-aplus-tests'); - -// tests - -var adapter = {}; -adapter.fulfilled = function (value) { - var p = new Promise; - p.fulfill(value); - return p; -}; -adapter.rejected = function (reason) { - var p = new Promise; - p.reject(reason); - return p; -} -adapter.deferred = function () { - var p = new Promise; - return { - promise: p, reject: p.reject.bind(p), resolve: p.fulfill.bind(p) - } -} - -it("run A+ suite", function (done) { - this.timeout(60000); - aplus(adapter, { - reporter: 'dot', slow: 1 - -// , bail:true -// , grep:'2.3.1: If `promise` and `x` refer to the same object, reject `promise` with a `TypeError` as the reason. via return from a fulfilled promise' - }, function (err) { - done(err); - }); -}); - diff --git a/server/node_modules/monk/package.json b/server/node_modules/monk/package.json deleted file mode 100755 index a08e72a5..00000000 --- a/server/node_modules/monk/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "monk", - "version": "1.0.1", - "main": "lib/monk.js", - "tags": [ - "mongodb", - "mongo", - "driver" - ], - "repository": { - "type": "git", - "url": "git://github.com/LearnBoost/monk.git" - }, - "dependencies": { - "mongoskin": "1.4.13", - "debug": "*", - "mpromise": "0.5.1" - }, - "devDependencies": { - "mocha": "*", - "expect.js": "0.1.x", - "promises-aplus-tests": "2.0.x" - }, - "scripts": { - "test": "make test" - }, - "gitHead": "4b0114440d91d1c570b30c713c3f4613e4b5933d", - "description": "[![build status](https://secure.travis-ci.org/Automattic/monk.png?branch=master)](https://secure.travis-ci.org/Automattic/monk)", - "bugs": { - "url": "https://github.com/LearnBoost/monk/issues" - }, - "homepage": "https://github.com/LearnBoost/monk", - "_id": "monk@1.0.1", - "_shasum": "56ad6623b5790fec4a5a69071fee7e75a2affac4", - "_from": "monk@", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "rauchg", - "email": "rauchg@gmail.com" - }, - "maintainers": [ - { - "name": "rauchg", - "email": "rauchg@gmail.com" - } - ], - "dist": { - "shasum": "56ad6623b5790fec4a5a69071fee7e75a2affac4", - "tarball": "http://registry.npmjs.org/monk/-/monk-1.0.1.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/monk/-/monk-1.0.1.tgz" -} diff --git a/server/node_modules/monk/test/collection.test.js b/server/node_modules/monk/test/collection.test.js deleted file mode 100755 index 3916b78e..00000000 --- a/server/node_modules/monk/test/collection.test.js +++ /dev/null @@ -1,549 +0,0 @@ -/*global expect*/ - -var monk = require('../lib/monk') - , immediately = global.setImmediate || process.nextTick - , db - , users, indexes; - -describe('collection', function () { - before(function () { - db = monk('127.0.0.1/monk'); - users = db.get('users-' + Date.now()); - indexes = db.get('indexes-' + Date.now()); - }); - - describe('casting method', function () { - it('string -> oid', function () { - var oid = users.id('4ee0fd75d6bd52107c000118'); - expect(oid.toHexString()).to.equal('4ee0fd75d6bd52107c000118'); - }); - - it('oid -> oid', function () { - var oid = users.id(users.id('4ee0fd75d6bd52107c000118')); - expect(oid.toHexString()).to.equal('4ee0fd75d6bd52107c000118'); - }); - - it('new oid', function () { - var oid = users.id(); - expect(oid.toHexString()).to.be.a('string'); - }); - - it('#oid', function(){ - var oid = users.oid(); - expect(oid.toHexString()).to.be.a('string'); - }); - }); - - describe('cast', function () { - it('should cast oids inside $and', function () { - var cast = users.cast({ - $and: [{_id: '4ee0fd75d6bd52107c000118'}] - }); - - var oid = users.id(cast.$and[0]._id); - expect(oid.toHexString()).to.equal('4ee0fd75d6bd52107c000118'); - }); - - it('should cast oids inside $nor', function () { - var cast = users.cast({ - $nor: [{_id: '4ee0fd75d6bd52107c000118'}] - }); - - var oid = users.id(cast.$nor[0]._id); - expect(oid.toHexString()).to.equal('4ee0fd75d6bd52107c000118'); - }); - - it('should cast oids inside $not queries', function () { - var cast = users.cast({$not: {_id: '4ee0fd75d6bd52107c000118'}}); - - var oid = users.id(cast.$not._id); - expect(oid.toHexString()).to.equal('4ee0fd75d6bd52107c000118'); - }); - }); - - describe('indexes', function () { - it('should accept a field string', function (done) { - users.index('name.first', function (err) { - expect(err).to.be(null); - users.indexes(function (err, indexes) { - expect(err).to.be(null); - expect(indexes['name.first_1']).to.not.be(undefined); - done(); - }); - }); - }); - - it('should accept space-delimited compound indexes', function (done) { - users.index('name last', function (err) { - expect(err).to.be(null); - users.indexes(function (err, indexes) { - expect(err).to.be(null); - expect(indexes.name_1_last_1).to.not.be(undefined); - done(); - }); - }); - }); - - it('should accept array compound indexes', function (done) { - users.index(['nombre', 'apellido'], function (err) { - expect(err).to.be(null); - users.indexes(function (err, indexes) { - expect(err).to.be(null); - expect(indexes.nombre_1_apellido_1).to.not.be(undefined); - done(); - }); - }); - }); - - it('should accept object compound indexes', function (done) { - users.index({ up: 1, down: -1 }, function (err) { - expect(err).to.be(null); - users.indexes(function (err, indexes) { - expect(err).to.be(null); - expect(indexes['up_1_down_-1']).to.not.be(undefined); - done(); - }); - }); - }); - - it('should accept options', function (done) { - indexes.index({ woot: 1 }, { unique: true }, function (err) { - expect(err).to.be(null); - indexes.indexes(function (err, indexes) { - expect(err).to.be(null); - expect(indexes.woot_1).to.not.be(undefined); - done(); - }); - }); - }); - }); - - describe('inserting', function () { - it('should force callback in next tick', function (done) { - var p = users.insert({ a: 'b' }); - p.complete(done); - }); - - it('should give you an object with the _id', function (done) { - var p = users.insert({ a: 'b' }, function (err, obj) { - expect(obj._id).to.be.an('object'); - expect(obj._id.toHexString).to.not.be(undefined); - done(); - }); - }); - - it('should return an array if an array was inserted', function (done) { - var p = users.insert([{ a: 'b' }, { b: 'a' }], function (err, docs) { - expect(docs).to.be.an('array'); - expect(docs.length).to.be(2); - done(); - }); - }); - }); - - describe('finding', function () { - it('should find by id', function (done) { - users.insert({ c: 'd' }, function (err, doc) { - expect(err).to.be(null); - users.findById(doc._id, function (err, doc) { - expect(err).to.be(null); - expect(doc.c).to.be('d'); - done(); - }); - }); - }); - - it('should only provide selected fields', function (done) { - users.insert({ a: 'b', c: 'd', e: 'f' }, function (err, doc) { - expect(err).to.be(null); - users.findOne(doc._id, 'a e', function (err, doc) { - expect(err).to.be(null); - expect(doc.a).to.be('b'); - expect(doc.e).to.be('f'); - expect(doc.c).to.be(undefined); - done(); - }); - }); - }); - - it('should work with streaming', function (done) { - var query = { a: { $exists: true } } - , found = 0; - users.count(query, function (err, total) { - users.find(query) - .each(function (doc) { - expect(doc.a).to.not.eql(null); - found++; - }) - .error(function (err) { - done(err); - }) - .success(function () { - expect(found).to.be(total); - done(); - }); - }); - }); - - it('should work with streaming option', function (done) { - var query = { a: { $exists: true } } - , found = 0; - users.count(query, function (err, total) { - var promise = users.find(query, { stream: true }); - immediately(function () { - promise - .each(function (doc) { - expect(doc.a).to.not.eql(null); - found++; - }) - .error(function (err) { - done(err); - }) - .success(function () { - expect(found).to.be(total); - done(); - }); - }); - }); - }); - - it('should allow stream cursor destroy', function(done){ - var query = { a: { $exists: true } } - , found = 0; - users.count(query, function (err, total) { - if (total <= 1) throw new Error('Bad test'); - var cursor = users.find(query) - .each(function (doc) { - expect(doc.a).to.not.eql(null); - found++; - if (2 == found) cursor.destroy(); - }) - .error(function (err) { - done(err); - }) - .success(function () { - setTimeout(function() { - expect(found).to.be(2); - done(); - }, 100); - }); - }); - }); - }); - - describe('counting', function () { - it('should work', function (done) { - users.count({ a: 'counting' }, function (err, count) { - expect(err).to.be(null); - expect(count).to.be(0); - - users.insert({ a: 'counting' }, function (err) { - expect(err).to.be(null); - - users.count({ a: 'counting' }, function (err, count) { - expect(err).to.be(null); - expect(count).to.be(1); - done(); - }); - }); - }); - }); - }); - - describe('distinct', function(){ - it('should work', function(done){ - users.insert({ distinct: 'a' }, function(err){ - expect(err).to.be(null); - users.insert({ distinct: 'a' }, function(err){ - expect(err).to.be(null); - users.insert({ distinct: 'b' }, function(err){ - expect(err).to.be(null); - users.distinct('distinct', function(err, docs){ - expect(err).to.be(null); - expect(docs).to.eql(['a', 'b']); - done(); - }); - }); - }); - }); - }); - }); - - describe('updating', function () { - it('should update', function (done) { - users.insert({ d: 'e' }, function (err, doc) { - expect(err).to.be(null); - var p = users.update({ _id: doc._id }, { $set: { d: 'f' } }); - p.complete(function (err) { - expect(err).to.be(null); - users.findById(doc._id, function (err, doc) { - expect(err).to.be(null); - expect(doc.d).to.be('f'); - done(); - }); - }); - }); - }); - it('should update by id', function (done) { - users.insert({ d: 'e' }, function (err, doc) { - expect(err).to.be(null); - var id = doc._id; - var p = users.updateById(id, { $set: { d: 'f' } }); - p.complete(function (err) { - expect(err).to.be(null); - users.findById(doc._id, function (err, doc) { - expect(err).to.be(null); - expect(doc.d).to.be('f'); - done(); - }); - }); - }); - }); - - it('should work with an objectid', function (done) { - users.insert({ worked: false }, function (err, doc) { - expect(err).to.be(null); - users.update(doc._id, { $set: { worked: true } }, function (err) { - expect(err).to.be(null); - users.findOne(doc._id, function (err, doc) { - expect(err).to.be(null); - expect(doc.worked).to.be(true); - done(); - }); - }); - }); - }); - - it('should work with an objectid (string)', function (done) { - users.insert({ worked: false }, function (err, doc) { - expect(err).to.be(null); - users.update(doc._id.toString(), { $set: { worked: true } }, function (err) { - expect(err).to.be(null); - users.findOne(doc._id, function (err, doc) { - expect(err).to.be(null); - expect(doc.worked).to.be(true); - done(); - }); - }); - }); - }); - }); - - describe('remove', function () { - it('should remove a document', function (done) { - users.insert({ name: 'Tobi' }, function (err, doc) { - if (err) return done(err); - users.remove({ name: 'Tobi' }, function (err) { - if (err) return done(err); - users.find({ name: 'Tobi' }, function (err, doc) { - if (err) return done(err); - expect(doc).to.eql([]); - done(); - }); - }); - }); - }); - it('should remove a document by id', function (done) { - users.insert({ name: 'Tobi' }, function (err, doc) { - if (err) return done(err); - var id = doc._id; - users.removeById(id, function (err) { - if (err) return done(err); - users.findById(id, function (err, doc) { - if (err) return done(err); - expect(doc).to.be.null; - done(); - }); - }); - }); - }); - }); - - describe('findAndModifying', function () { - it('should alter an existing document', function (done) { - var rand = 'now-' + Date.now(); - users.insert({ find: rand }, function (err, doc) { - expect(err).to.be(null); - users.findAndModify({ find: rand }, { find: 'woot' }, { new: true }, function (err, doc) { - expect(err).to.be(null); - expect(doc.find).to.be('woot'); - users.findById(doc._id, function (err, found) { - expect(err).to.be(null); - expect(found._id.toString()).to.equal(doc._id.toString()); - expect(found.find).to.be('woot'); - done(); - }); - }); - }); - }); - - it('should accept an id as query param', function(done){ - users.insert({ locate: 'me' }, function(err, user){ - expect(err).to.be(null); - users.findAndModify(user._id, { $set: { locate: 'you' } }, function(err){ - expect(err).to.be(null); - users.findOne(user._id, function(err, user){ - expect(err).to.be(null); - expect(user.locate).to.be('you'); - done(); - }); - }); - }); - }); - - it('should accept an id as query param (mongo syntax)', function(done){ - users.insert({ locate: 'me' }, function(err, user){ - expect(err).to.be(null); - users.findAndModify({ query: user._id, update: { $set: { locate: 'you' } } }, function(err){ - expect(err).to.be(null); - users.findOne(user._id, function(err, user){ - expect(err).to.be(null); - expect(user.locate).to.be('you'); - done(); - }); - }); - }); - }); - - it('should upsert', function (done) { - function callback (err, doc) { - if (err) return done(err); - expect(doc.find).to.be(rand); - users.findOne({ find: rand }, function (err, found) { - expect(err).to.be(null); - expect(found._id.toString()).to.be(doc._id.toString()); - expect(found.find).to.be(rand); - done(); - }); - } - - var rand = 'now-' + Date.now(); - - users.findAndModify( - { find: rand } - , { find: rand } - , { upsert: true } - , callback - ); - }); - }); - - describe('options', function () { - it('should allow defaults', function (done) { - db.options.multi = true; - users.update({}, { $set: { f: 'g' } }, function (err, num) { - expect(err).to.be(null); - expect(num).to.be.a('number'); // only a number of multi=true - - users.options.safe = false; - users.options.multi = false; - users.update({}, { $set: { g: 'h' } }, function (err, num) { - expect(err).to.be(null); - expect(num).to.be(null); - - users.options.safe = true; - users.options.multi = true; - users.update({}, { $set: { g: 'h' } }, { safe: false, multi: false }, function (err, num) { - expect(err).to.be(null); - expect(num).to.be(null); - done(); - }); - }); - }); - }); - }); - - describe('promises', function () { - var Promise = monk.Promise; - - it('insert', function () { - var p = users.insert(); - expect(p).to.be.a(Promise); - expect(p.col).to.be(users); - expect(p.type).to.be('insert'); - }); - - it('findOne', function () { - var p = users.findOne(); - expect(p).to.be.a(Promise); - expect(p.col).to.be(users); - expect(p.type).to.be('findOne'); - }); - - it('find', function () { - var p = users.findOne(); - expect(p).to.be.a(Promise); - expect(p.col).to.be(users); - expect(p.type).to.be('findOne'); - }); - - it('update', function () { - var p = users.findOne(); - expect(p).to.be.a(Promise); - expect(p.col).to.be(users); - expect(p.type).to.be('findOne'); - }); - - it('findAndModify', function () { - var p = users.findAndModify(); - expect(p).to.be.a(Promise); - expect(p.col).to.be(users); - expect(p.type).to.be('findAndModify'); - }); - - it('remove', function () { - var p = users.remove(); - expect(p).to.be.a(Promise); - expect(p.col).to.be(users); - expect(p.type).to.be('remove'); - }); - - it('index', function () { - var p = users.index('eee'); - expect(p).to.be.a(Promise); - expect(p.col).to.be(users); - expect(p.type).to.be('index'); - }); - - it('indexes', function () { - var p = users.indexes(); - expect(p).to.be.a(Promise); - expect(p.col).to.be(users); - expect(p.type).to.be('indexes'); - }); - - it('drop', function (done) { - var col = db.get('drop-' + Date.now()); - col.insert({}, function (err) { - expect(err).to.be(null); - var p = col.drop(done); - expect(p).to.be.a(Promise); - expect(p.type).to.be('drop'); - }); - }); - - it('options', function () { - var p = users.find({}, '-test'); - expect(p.opts).to.eql({ fields: { test: 0 }, safe: true, multi: true }); - }); - - it('query', function(done){ - var qry = { a: 'woot' }; - var p = users.find(qry); - expect(p.query).to.be(qry); - p.once('complete', function(){ - setTimeout(function(){ - expect(p.qry).to.be(undefined); - done(); - }, 50); - }); - }); - }); - - after(function (done) { - users.drop(function (err) { - expect(err).to.be(null); - indexes.drop(done); - }); - }); -}); diff --git a/server/node_modules/monk/test/common.js b/server/node_modules/monk/test/common.js deleted file mode 100755 index 81373dbf..00000000 --- a/server/node_modules/monk/test/common.js +++ /dev/null @@ -1,6 +0,0 @@ - -/** - * Expose expect.js - */ - -expect = require('expect.js'); diff --git a/server/node_modules/monk/test/monk.test.js b/server/node_modules/monk/test/monk.test.js deleted file mode 100755 index f918f891..00000000 --- a/server/node_modules/monk/test/monk.test.js +++ /dev/null @@ -1,71 +0,0 @@ -/*global expect*/ - -var monk = require('../lib/monk'); - -describe('monk', function () { - - describe('constructor', function () { - it('Manager', function () { - expect(monk).to.be.a('function'); - expect(monk.name).to.be('Manager'); - }); - - it('Collection', function () { - expect(monk.Collection).to.be.a('function'); - expect(monk.Collection.name).to.be('Collection'); - }); - - it('Promise', function () { - expect(monk.Promise).to.be.a('function'); - expect(monk.Promise.name).to.be('Promise'); - }); - }); - - describe('connection', function () { - it('to a regular server', function (done) { - monk('127.0.0.1/monk-test', done); - }); - - it('to a replica set (array)', function (done) { - monk(['127.0.0.1/monk-test', 'localhost/monk-test'], done); - }); - - it('to a replica set (string)', function (done) { - monk('127.0.0.1,localhost/monk-test', done); - }); - - it('followed by disconnection', function (done) { - var db = monk('127.0.0.1/monk-test', function () { - db.close(done); - }); - }); - }); - - describe('collections', function () { - var Collection = monk.Collection; - var db = monk('127.0.0.1/monk-test'); - - it('Manager#get', function () { - expect(db.get('users')).to.be.a(Collection); - }); - - it('Manager#col', function(){ - expect(db.col('users')).to.be.a(Collection); - }); - }); - - describe('ObjectID casting', function(){ - var db = monk('127.0.0.1/monk-test'); - - it('Manager#id', function(){ - var oid = db.id(); - expect(oid.toHexString()).to.be.a('string'); - }); - - it('Manager#oid', function(){ - var oid = db.oid(); - expect(oid.toHexString()).to.be.a('string'); - }); - }); - -}); diff --git a/server/node_modules/monk/test/promise.test.js b/server/node_modules/monk/test/promise.test.js deleted file mode 100755 index 12bfce93..00000000 --- a/server/node_modules/monk/test/promise.test.js +++ /dev/null @@ -1,128 +0,0 @@ - -var Promise = require('../lib/monk').Promise - -describe('promise', function () { - - it('Promise#type', function () { - var p = new Promise(null, 'woot'); - expect(p.type).to.be('woot'); - }); - - it('Promise#error', function () { - var p = new Promise() - p.error(function(){}); - // 2 due to internal event listener - expect(p.listeners('error').length).to.be(2); - }); - - it('Promise#success', function () { - var p = new Promise() - p.success(function(){}); - // 2 due to internal event listener - expect(p.listeners('success').length).to.be(2); - }); - - it('Promise#complete', function () { - var p = new Promise() - p.complete(function(){}); - // 2 due to internal event listener - expect(p.listeners('error').length).to.be(2); - expect(p.listeners('success').length).to.be(2); - }); - - it('Promise#each', function () { - var p = new Promise() - p.each(function(){}); - expect(p.listeners('each').length).to.be(1); - }); - - it('Promise#then', function () { - var p = new Promise() - , runCount = 0; - - p.then(function() { - ++runCount; - }); - - p.fulfill(); - - setTimeout(function () { - expect(runCount).to.be(1); - }, 10); - }); - - it('Promise#then-chain', function () { - var p = new Promise() - , runCount = 0; - - p.then(function () { - ++runCount; - return (new Promise()).fulfill(); - }).then(function () { - ++runCount; - }); - - p.fulfill(); - - setTimeout(function () { - expect(runCount).to.be(2); - }, 10); - }); - - it('Promise#reject', function (done) { - var p = new Promise() - p.error(function(err){ - expect(err).to.be('foo'); - done(); - }); - p.reject('foo'); - }); - - it('Promise#fulfill', function (done) { - var p = new Promise() - p.success(function(data){ - expect(data).to.be('bar'); - done(); - }); - p.fulfill('bar'); - }); - - it('Promise#resolve-err', function (done) { - var p = new Promise() - p.complete(function(err, data){ - expect(err).to.be('foo'); - done(); - }); - p.resolve('foo'); - }); - - it('Promise#resolve-data', function (done) { - var p = new Promise() - p.complete(function(err, data){ - expect(err).to.not.be.ok(); - expect(data).to.be('bar'); - done(); - }); - p.resolve(null, 'bar'); - }); - - it('Promise#complete-err', function (done) { - var p = new Promise() - p.on('complete', function(err, data){ - expect(err).to.be('foo'); - done(); - }); - p.resolve('foo'); - }); - - it('Promise#complete-data', function (done) { - var p = new Promise() - p.on('complete', function(err, data){ - expect(err).to.not.be.ok(); - expect(data).to.be('bar'); - done(); - }); - p.resolve(null, 'bar'); - }); - -}); diff --git a/server/node_modules/monk/test/promises-A.js b/server/node_modules/monk/test/promises-A.js deleted file mode 100755 index 5d60d279..00000000 --- a/server/node_modules/monk/test/promises-A.js +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Module dependencies. - */ - -var Promise = require('../lib/monk').Promise; -var aplus = require('promises-aplus-tests'); - -var adapter = { - deferred: function () { - var p = new Promise(); - return { - promise: p, - reject: p.reject, - resolve: p.fulfill - }; - } -}; - -describe("Promises/A+ Tests", function () { - aplus.mocha(adapter); -}); diff --git a/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/.npmignore b/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/.npmignore old mode 100755 new mode 100644 diff --git a/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/.travis.yml b/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/.travis.yml old mode 100755 new mode 100644 index a6e97419..a505004b --- a/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/.travis.yml +++ b/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/.travis.yml @@ -1,14 +1,18 @@ +sudo: false language: node_js node_js: - - "0.8" + - "0.12" - "0.10" - - "0.11" + - "0.8" + - "iojs" before_install: - - "npm install -g npm@1.4.x" + - 'if [ "${TRAVIS_NODE_VERSION}" == "0.8" ]; then npm install -g npm@2.11.1; fi' script: - "npm run test-travis" after_script: - "npm install coveralls@2.11.x && cat coverage/lcov.info | coveralls" +matrix: + fast_finish: true notifications: irc: channels: diff --git a/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/README.md b/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/README.md old mode 100755 new mode 100644 diff --git a/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/index.js b/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/index.js old mode 100755 new mode 100644 index f0e8113e..af17ab7c --- a/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/index.js +++ b/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/index.js @@ -1,5 +1,7 @@ 'use strict'; +var has = Object.prototype.hasOwnProperty; + /** * An auto incrementing id which we can use to create "unique" Ultron instances * so we can track the event emitters that are added through the Ultron @@ -77,9 +79,7 @@ Ultron.prototype.remove = function remove() { args = []; for (event in this.ee._events) { - if (this.ee._events.hasOwnProperty(event)) { - args.push(event); - } + if (has.call(this.ee._events, event)) args.push(event); } } @@ -89,6 +89,10 @@ Ultron.prototype.remove = function remove() { for (var j = 0; j < listeners.length; j++) { event = listeners[j]; + // + // Once listeners have a `listener` property that stores the real listener + // in the EventEmitter that ships with Node.js. + // if (event.listener) { if (event.listener.__ultron !== this.id) continue; delete event.listener.__ultron; diff --git a/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/package.json b/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/package.json old mode 100755 new mode 100644 index 0c85ad1f..32406cfb --- a/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/package.json +++ b/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/package.json @@ -1,13 +1,14 @@ { "name": "ultron", - "version": "1.0.1", + "version": "1.0.2", "description": "Ultron is high-intelligence robot. It gathers intel so it can start improving upon his rudimentary design", "main": "index.js", "scripts": { - "test": "mocha --reporter spec --ui bdd test.js", - "watch": "mocha --watch --reporter spec --ui bdd test.js", - "coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter spec --ui bdd test.js", - "test-travis": "istanbul cover node_modules/.bin/_mocha --report lcovonly -- --reporter spec --ui bdd test.js" + "100%": "istanbul check-coverage --statements 100 --functions 100 --lines 100 --branches 100", + "test": "mocha test.js", + "watch": "mocha --watch test.js", + "coverage": "istanbul cover ./node_modules/.bin/_mocha -- test.js", + "test-travis": "istanbul cover node_modules/.bin/_mocha --report lcovonly -- test.js" }, "repository": { "type": "git", @@ -29,39 +30,22 @@ }, "license": "MIT", "devDependencies": { - "assume": "0.0.x", - "eventemitter3": "0.1.x", + "assume": "1.2.x", + "eventemitter3": "1.1.x", "istanbul": "0.3.x", - "mocha": "2.0.x", - "pre-commit": "0.0.x" + "mocha": "2.2.x", + "pre-commit": "1.0.x" }, "bugs": { "url": "https://github.com/unshiftio/ultron/issues" }, "homepage": "https://github.com/unshiftio/ultron", - "gitHead": "1aae6f07661ebb69a60c466ef50b9798cfb7f631", - "_id": "ultron@1.0.1", - "_shasum": "c9d8d86c9cf2823028eb45629ab725897dd65dc5", - "_from": "ultron@1.0.x", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "V1", - "email": "info@3rd-Eden.com" - }, - "maintainers": [ - { - "name": "V1", - "email": "info@3rd-Eden.com" - }, - { - "name": "unshift", - "email": "npm@unshift.io" - } - ], + "readme": "# Ultron\n\n[![Made by unshift](https://img.shields.io/badge/made%20by-unshift-00ffcc.svg?style=flat-square)](http://unshift.io)[![Version npm](http://img.shields.io/npm/v/ultron.svg?style=flat-square)](http://browsenpm.org/package/ultron)[![Build Status](http://img.shields.io/travis/unshiftio/ultron/master.svg?style=flat-square)](https://travis-ci.org/unshiftio/ultron)[![Dependencies](https://img.shields.io/david/unshiftio/ultron.svg?style=flat-square)](https://david-dm.org/unshiftio/ultron)[![Coverage Status](http://img.shields.io/coveralls/unshiftio/ultron/master.svg?style=flat-square)](https://coveralls.io/r/unshiftio/ultron?branch=master)[![IRC channel](http://img.shields.io/badge/IRC-irc.freenode.net%23unshift-00a8ff.svg?style=flat-square)](http://webchat.freenode.net/?channels=unshift)\n\nUltron is a high-intelligence robot. It gathers intelligence so it can start\nimproving upon his rudimentary design. It will learn your event emitting\npatterns and find ways to exterminate them. Allowing you to remove only the\nevent emitters that **you** assigned and not the ones that your users or\ndevelopers assigned. This can prevent race conditions, memory leaks and even file\ndescriptor leaks from ever happening as you won't remove clean up processes.\n\n## Installation\n\nThe module is designed to be used in browsers using browserify and in Node.js.\nYou can install the module through the public npm registry by running the\nfollowing command in CLI:\n\n```\nnpm install --save ultron\n```\n\n## Usage\n\nIn all examples we assume that you've required the library as following:\n\n```js\n'use strict';\n\nvar Ultron = require('ultron');\n```\n\nNow that we've required the library we can construct our first `Ultron` instance.\nThe constructor requires one argument which should be the `EventEmitter`\ninstance that we need to operate upon. This can be the `EventEmitter` module\nthat ships with Node.js or `EventEmitter3` or anything else as long as it\nfollow the same API and internal structure as these 2. So with that in mind we\ncan create the instance:\n\n```js\n//\n// For the sake of this example we're going to construct an empty EventEmitter\n//\nvar EventEmitter = require('events').EventEmitter; // or require('eventmitter3');\nvar events = new EventEmitter();\n\nvar ultron = new Ultron(events);\n```\n\nYou can now use the following API's from the Ultron instance:\n\n### Ultron.on\n\nRegister a new event listener for the given event. It follows the exact same API\nas `EventEmitter.on` but it will return itself instead of returning the\nEventEmitter instance. If you are using EventEmitter3 it also supports the\ncontext param:\n\n```js\nultron.on('event-name', handler, { custom: 'function context' });\n```\n\n### Ultron.once\n\nExactly the same as the [Ultron.on](#ultronon) but it only allows the execution\nonce.\n\n### Ultron.remove\n\nThis is where all the magic happens and the safe removal starts. This function\naccepts different argument styles:\n\n- No arguments, assume that all events need to be removed so it will work as\n `removeAllListeners()` API.\n- 1 argument, when it's a string it will be split on ` ` and `,` to create a\n list of events that need to be cleared.\n- Multiple arguments, we assume that they are all names of events that need to\n be cleared.\n\n```js\nultron.remove('foo, bar baz'); // Removes foo, bar and baz.\nultron.remove('foo', 'bar', 'baz'); // Removes foo, bar and baz.\nultron.remove(); // Removes everything.\n```\n\nIf you just want to remove a single event listener using a function reference\nyou can still use the EventEmitter's `removeListener(event, fn)` API:\n\n```js\nfunction foo() {}\n\nulton.on('foo', foo);\nevents.removeListener('foo', foo);\n```\n\n## License\n\nMIT\n", + "readmeFilename": "README.md", + "_id": "ultron@1.0.2", "dist": { - "shasum": "c9d8d86c9cf2823028eb45629ab725897dd65dc5", - "tarball": "http://registry.npmjs.org/ultron/-/ultron-1.0.1.tgz" + "shasum": "f6a1668f5620a7922b6ed3bae6a7a25da8b47ded" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/ultron/-/ultron-1.0.1.tgz" + "_from": "ultron@1.0.2", + "_resolved": "https://registry.npmjs.org/ultron/-/ultron-1.0.2.tgz" } diff --git a/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/test.js b/server/node_modules/socket.io/node_modules/engine.io/node_modules/ws/node_modules/ultron/test.js old mode 100755 new mode 100644 diff --git a/server/package.json b/server/package.json index 70344eef..7880fd21 100755 --- a/server/package.json +++ b/server/package.json @@ -1,9 +1,15 @@ { - "name": "zoffbackend", - "version": "0.0.1", + "name": "zoff", + "version": "2.0.1", "description": "Zöff, the shared YouTube based radio services", "dependencies": { "express": "^4.10.2", - "socket.io": "^1.3.5" + "socket.io": "^1.3.5", + "shortid": "^2.2.2", + "mongojs": "^0.18.2" + }, + "author": { + "name": "Kasper Rynning Tønnesen", + "email": "kasper@kasperrt.no" } }